I have troubles with traversing through a array binary tree without recursion. I hope someone can tell me what iam doing wrong. For simplicity the code is kept simple.
Please note: Its not allowed to add other methods like Iterator to check if there is a hasNext() and so on.
For now i just want to print all keys out (incl. child keys) in the hope that i can do the rest of the learning!
Thank you very much for helping.
public class BTree {
private Node root;
public BTree(Node root) {
this.root = root;
}
public int getMaxKey() {
Node copy = root;
for (int i = 0; copy.child != null && i < copy.child.length; i++) {
System.out.println("key: " + copy.key); // output: 15, 80
if (copy.child != null) {
copy = copy.child[i];
}
}
return 0;
}
}
public class Node {
public int key;
public Node[] child;
public Node(int key, Node[] child) {
this.key = key;
this.child = child;
}
}
public class NodeMain {
public static void main(String[] args) {
Node[] lv1Nodes = new Node[2];
lv1Nodes[0] = new Node(25, null);
lv1Nodes[1] = new Node(99, null);
Node[] lv0Nodes = new Node[2];
lv0Nodes[0] = new Node(80, lv1Nodes);
lv0Nodes[1] = new Node(5, null);
Node root = new Node(15, lv0Nodes);
BTree bTree = new BTree(root);
int maxKey = bTree.getMaxKey(); // output should be 99
System.out.println(maxKey);
}
}
