【发布时间】:2021-04-15 06:09:39
【问题描述】:
我正在编写一个递归程序以在 Preorder 中遍历 BinaryTree。这是 BinaryTree 类定义
public class BinaryTree {
private int data;
private BinaryTree left,right;
public BinaryTree(int data){
this.data = data;
this.left = null;
this.right = null;
}
public int getData(){
return data;
}
public BinaryTree getLeft() {
return left;
}
public BinaryTree getRight() {
return right;
}
public void setData(int data) {
this.data = data;
}
public void setLeft(BinaryTree left) {
this.left = left;
}
public void setRight(BinaryTree right) {
this.right = right;
}
}
这是我的测试程序
public class TreeTest {
public static void main(String[] args){
TreeTest treeTest = new TreeTest();
treeTest.preTraversal(treeTest.getBinaryTree());
}
public void preTraversal(BinaryTree binaryTree){
while(binaryTree!=null){
System.out.println(binaryTree.getData()+" ");
preTraversal(binaryTree.getLeft());
preTraversal(binaryTree.getRight());
}
}
//Tree creation
public BinaryTree getBinaryTree(){
BinaryTree root = new BinaryTree(1);
BinaryTree node2 = new BinaryTree(2);
BinaryTree node3 = new BinaryTree(3);
root.setLeft(node2);
root.setRight(node3);
return root;
}
}
问题是程序永远不会停止。这是输出。
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
【问题讨论】:
标签: algorithm data-structures binary-tree preorder