我正在尝试使用按顺序遍历来实现二叉搜索树。我试图在彼此之后打印一系列数字来测试它。它似乎排序很好,但它有时打印出来的数字。看看我的代码的相关部分:
树类和方法:
public class Tree {
Node root;
public Tree(){
root = null;
}
public Node add(Node n, int value){
if(n== null){
n= new Node(value);
}else if(value < n.getValue()){
n.addLeftNode(add(n.getLeft(),value));
}else if(value > n.getValue()){
n.addRightNode(add(n.getRight(),value));
}
return n;
}
public static Node traverse(Node n){
Node result = new Node();
if(n != null){
if(n.getLeft() != null){
result = traverse(n.getLeft());
System.out.println(result.getValue());
}
result = n;
System.out.println(result.getValue());
if(n.getRight() != null){
result = traverse(n.getRight());
System.out.println(result.getValue());
}
}
return result;
}
}
这就是它打印出来的内容:
0 0 1 1 3 4 4 五 6 7 7 8 10 11 12 12 12 15 15 15 15 15 15 15 16 18 18 20 21 22 22 22 22 23 27 28 28 28 29 34 35 43 43 43 43 43 43 43 44 45 45 55 56 59 66 75 75 75 75 75 75 76 76 76 78 88 89 89 90 90 90 98 98
任何线索?我猜测它是遍历的东西。尝试调试它然而我仍然无法找到问题。如你所见,Nos至少是排序的。
答案 0 :(得分:1)
当您向左或向右移动时,调用遍历将打印左/右节点。您无需分别左右打印。
if(n != null){
if(n.getLeft() != null){
result = traverse(n.getLeft());
// System.out.println(result.getValue());
}
result = n;
System.out.println(result.getValue()); // This prints the left and right via recursion into traverse(...)
if(n.getRight() != null){
result = traverse(n.getRight());
// System.out.println(result.getValue());
}
}
答案 1 :(得分:0)
遍历方法应该是:
void traverse(Node n) {
if(n == null)
return;
traverse(n.getLeft());
System.out.println(n.getValue());
traverse(n.getRight());
}