如何为二叉树实现编写正确的inorder方法?
这是我的尝试:
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));
}
}
}
答案 0 :(得分:1)
myTree.inorder(0); //参数:0
inorder((node * 2)); // node = 0,node * 2 = 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) + 1);
System.out.print(tree[node] + " ");
inorder(((node * 2) + 2));
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.inorder(0);
}
}