Why cant I initialize the binary tree in main? public class TreeNode { //root node Node root;
Fantastic news! We've Found the answer you've been seeking!
Question:
public class TreeNode {
//root node
Node root;
//method to add nodes
public void addNode(int key, String name) {
//initialize new node
Node newNode = new Node(key, name);
/*
* checks to see if its indeed the root element
* and if it throw newNode to it
*/
if(root == null) {
root = newNode;
} else {
/*
* else if not the root element
* we will create. another node and set root
* as the node because we will start with root as we
* traverse through our tree
*/
Node focusNode = root;
//Future parent for new node
Node parent;
while(true) {
// is the root because thats where we will start
parent = focusNode;
//checks to see if the new node should on the left side
if(key < focusNode.key) {
// if the left child has no children
focusNode = focusNode.leftChild;
//then place the new node on the left of it
if (focusNode == null) {
parent.leftChild = newNode;
return;
}
}
// If we get here we know our node needs to go on the right
else {
focusNode = focusNode.rightChild;
// if the right child has no children
// we create. a new node
if(focusNode == null) {
//new node placed on the right side
parent.rightChild = newNode;
return;
}
}
}
}
}
//All nodes are visited in ascending order
// Recursin is used to go to one node
// and then go to its child nodes and so forth
public void inOrderTraverseTree (Node focusNode) {
//check to see if there is something in there
if(focusNode != null) {
//traverse the left node
inOrderTraverseTree(focusNode.leftChild);
// then we will visit the currently focused on
// node because we know that will be the next value
// of the lowest value
System.out.println(focusNode);
//then we traverse the right child
inOrderTraverseTree(focusNode.rightChild);
}
}
public static void main(String[] args) {
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
BinaryTree theTree = new BinaryTree();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//adding nodes
theTree.addNode(50, "boss");
theTree.addNode(46, "Vice Press");
theTree.addNode(44, "Officer manager");
theTree.addNode(32, "Secretary");
theTree.addNode(34, "Sales Manager");
theTree.addNode(27, "Salesman 1");
theTree.inOrderTraverseTree(theTree.root);
}
}
//How we will setup our different keys
class Node{
int key;
String name;
//reference to each child in the BINARY tree
Node leftChild;
Node rightChild;
//construct
Node(int key, String name)
{
this.key = key;
this.name = name;
}
//not needed but helpful to print out on screen
public String toString()
{
return name + "has a key " + key;
}
}
Related Book For
Introduction to Java Programming, Comprehensive Version
ISBN: 978-0133761313
10th Edition
Authors: Y. Daniel Liang
Posted Date: