QuestionQuestion

Make a Binary tree, where every node in the tree is a class node that needs to contain a data element of generic types, and a reference to their children. I also need to make methods to add "children" and delete nodes.

The method "findNode" to find elements in the tree, ex find(4) you should get the value 4 back, if it exists. else you get null.

The last thing that needs to be implemented is recursive methods to print out the tree: preOrder, postOrder and inOrder.

Solution PreviewSolution Preview

This material may consist of step-by-step explanations on how to solve a problem or examples of proper writing, including the use of citations, references, bibliographies, and formatting. This material is made available for the sole purpose of studying and learning - misuse is strictly forbidden.

public class BinaryTree <T extends Comparable<T>> {

class Node<T extends Comparable<T>> //Class that holds data for every node
{
private T data; //data
private Node<T> left, right; //children

public Node(T data) //Initialize new node
{
this.data = data;
left = null;
right = null;
}
}

private Node<T> root; //Tree root

public BinaryTree() //Initialize tree
{
root = null;
}

public void insert(T data) //insert data
{
Node<T> newNode = new Node<T>(data); //Create new node with data
if(root == null) //Check if tree has anything, if not store as root
root = newNode;
else
{
Node<T> prev = null;
Node<T> temp = root;
while(temp != null) //Go through all nodes in binary fashion, if data is greater than current node, go right else go left, until you hit an empty slot
{
prev = temp;
if(newNode.data.compareTo(temp.data) >= 0)
temp = temp.right;
else
temp = temp.left;
}
if(newNode.data.compareTo(prev.data) >= 0) //Place new node back, in empty spot for parent
prev.right = newNode;
else
prev.left = newNode;
}
}

private void insert(Node<T> node) //Same code, but only for inserting a full node (needed for deletion)
{
if(root == null)
{
root = node;
return;
}
else
{
Node<T> prev = null;
Node<T> temp = root;
while(temp != null)
{
prev = temp;
if(node.data.compareTo(temp.data) >= 0)
temp = temp.right;
else
temp = temp.left;
}
if(node.data.compareTo(prev.data) >= 0)
prev.right = node;
else
prev.left = node;
}
}...
$40.00 for this solution

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available Java Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Decision:
Upload a file
Continue without uploading

SUBMIT YOUR HOMEWORK
We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats