I'm currently solving this binary tree(not binary search tree) problem for my data structure class. However, when I tried to print the tree from root, debugging shows that root it still null even through I initialized my tree
public class Node {
int integerValue = 0;
public Node leftNode = null;
public Node rightNode = null;
public Node (int inputInt){
this.integerValue = inputInt;
}
}
insert the array element in the tree knowing there will be no delete or add
public class BinaryTree {
public void initializeTree(int[]string, int length, int currentPosition, Node currentNode){
if(currentPosition < length){
Node newNode = new Node(string[currentPosition]);
currentNode = newNode;
initializeTree(string,length, 2*currentPosition +1, currentNode.leftNode);
initializeTree(string,length, 2*currentPosition +2, currentNode.rightNode);
}
}
public void printTree(Node root){
if(root != null){
System.out.print(root.integerValue + " ");
printTree(root.leftNode);
printTree(root.rightNode);
}
}
}
public class Main {
public static void main(String[] args) {
int [] array = {0,1,2};
ArrayTree tree = new ArrayTree();
BinaryTree bTree = new BinaryTree();
Node root = null;
Node currentNode = root;
bTree.initializeTree(array, 3, 0, currentNode);
bTree.printTree(root);
}
}