Any thoughts why this wouldn't work. when using the commented line instead of the previous, Entire Binary tree is not getting printed but just the root node.
public class BinaryTreePractise {
Node root;
public void addNode(int age, String name){
Node node = new Node(age, name);
if (root ==null){
root = node;
return;
}
else {
Node focusNode = root;
while (true) {
Node parent = focusNode;
if (age < focusNode.age) {
focusNode = focusNode.leftChild;
if ( focusNode == null){
parent.leftChild = node; // working code
focusNode = node; // any thoughts why this wouldn't work instead of the above
return;
}
}
else {
focusNode = focusNode.rightChild;
if ( focusNode == null) {
parent.rightChild = node; // working code
focusNode = node; // any thoughts why this wouldn't work instead of the above
return;
}
}
}
}
}
class Node {
int age;
String name;
Node leftChild;
Node rightChild;
Node(int age, String name){
this.age = age;
this.name = name;
}
public String toString(){
return name + "has the age" + age;
}
}
public void inOrderTraversal(Node focusNode){
if(focusNode !=null) {
inOrderTraversal(focusNode.leftChild);
System.out.println(focusNode);
inOrderTraversal(focusNode.rightChild);
}
}
public static void main(String[] args){
BinaryTreePractise binaryTreePractise = new BinaryTreePractise();
binaryTreePractise.addNode(15, "A");
binaryTreePractise.addNode(85, "B");
binaryTreePractise.addNode(40, "C");
binaryTreePractise.addNode(50, "D");
binaryTreePractise.addNode(95, "E");
binaryTreePractise.addNode(25, "F");
binaryTreePractise.inOrderTraversal(binaryTreePractise.root);
}
}
Any thoughts why this wouldn't work. when using the commented line instead of the previous, Entire Binary tree is not getting printed but just the root node.