How to write a correct inorder-method for my binary-tree implementation?
This is my test-try:
class Main {
public static void main(String[] args) {
BinaryTree myTree = new BinaryTree();
myTree.inorder(0);
}
}
public class BinaryTree {
char[] tree = {'k', 'q', 'r', 'g', 'e', 'i', 'y', 'p', 'l', 'b', 'x', 'm', 'g', 't', 'u', 'v', 'z'};
public void inorder(int node) {
if(node < tree.length) {
inorder((node * 2));
System.out.print(tree[node] + " ");
inorder(((node * 2) + 1));
}
}
}
myTree.inorder(0); // parameter : 0
inorder((node * 2)); // node = 0, node * 2 = 0,
Therefore, the parameters will continue to be zero is an infinite loop.
public class BinaryTree {
char[] tree = {'k', 'q', 'r', 'g', 'e', 'i', 'y', 'p', 'l', 'b', 'x', 'm', 'g', 't', 'u', 'v', 'z'};
public void inorder(int node) {
if(node < tree.length) {
inorder((node * 2) + 1);
System.out.print(tree[node] + " ");
inorder(((node * 2) + 2));
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.inorder(0);
}
}