Question
I am writing a program Binary Search Tree using iterative and recursive method. For some reason nothing is printing for the recursive method. Can any
I am writing a program Binary Search Tree using iterative and recursive method. For some reason nothing is printing for the recursive method. Can any one help debug and fix the code?
package BinarySearchTree;
public class BinarySearchTree {
class Node{
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key, String name){
this.key = key;
this.name = name;
}
public String toString() {
return key + " has a key " + name;
}
}
Node root1;
Node root2;
public void addNodeIteratively(int key, String name) {
Node newNode1 = new Node(key,name);
if(root1 == null) {
root1 = newNode1;
}
else {
Node focusNode = root1;
Node parent;
while(true) {
parent = focusNode;
if(key < focusNode.key) {
focusNode = focusNode.leftChild;
if(focusNode == null) {
parent.leftChild = newNode1;
return;
}
}
else {
focusNode = focusNode.rightChild;
if(focusNode == null) {
parent.rightChild = newNode1;
return;
}
}
}
}
}
void insert(int key, String name) {
root2 = addNodeRecursively(root2, key, name);
}
public Node addNodeRecursively(Node root, int key, String name) {
if(root2 == null) {
root2 = new Node(key,name);
return root;
}
if(key < root2.key) {
root2.leftChild = addNodeRecursively(root2.leftChild, key, name);
}
else if(key > root2.key) {
root2.rightChild = addNodeRecursively(root2.rightChild, key, name);
}
return root;
}
void inOrder() {
inOrderRecursive(root2);
}
void inOrderRecursive(Node root2) {
if(root2 != null) {
inOrderRecursive(root2.leftChild);
System.out.println(root2.key);
inOrderRecursive(root2.rightChild);
}
}
public void inOrderTraversal(Node focusNode) {
if(focusNode != null) {
inOrderTraversal(focusNode.leftChild);
System.out.println(focusNode);
inOrderTraversal(focusNode.rightChild);
}
}
public static void main(String args[]) {
BinarySearchTree tree1 = new BinarySearchTree();
tree1.addNodeIteratively(4,"Manager");
tree1.addNodeIteratively(69, "Engineer");
tree1.addNodeIteratively(2, "Scientist");
tree1.addNodeIteratively(8, "Waiter");
tree1.addNodeIteratively(13, "Batman");
BinarySearchTree tree2 = new BinarySearchTree();
tree2.addNodeIteratively(4,"Manager");
tree2.addNodeIteratively(69, "Engineer");
tree2.addNodeIteratively(2, "Scientist");
tree2.addNodeIteratively(8, "Waiter");
tree2.addNodeIteratively(13, "Batman");
tree1.inOrderTraversal(tree1.root1);
tree2.inOrder();
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started