java - 二叉树遍历的问题

标签 java tree binary-tree tree-traversal

我正在尝试使用中序遍历来实现二叉搜索树。我正在尝试依次打印一系列数字来测试它。看起来它排序得很好,但有时会打印重复的数字。看看我的代码的相关部分:

树类和方法:

 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 5 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

有什么线索吗?我猜这与遍历有关。尝试调试它,但我仍然找不到问题。如您所见,编号至少已排序。

最佳答案

当你向左或向右遍历时,调用 traverse 将打印左/右节点。您不必分别打印左侧和右侧。

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());
    }
}

关于java - 二叉树遍历的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16269085/

相关文章:

java - 如何在 GUI 窗口间隔开的情况下启动 Eclipse 项目?

python - 如何在Python中的类中而不是类之外声明函数

algorithm - 设置绘制二叉树的位置

c - 在 C 中为二叉树实现 'insert' 函数

python - 如何在Python中解析和打印树

java - 使用 "in"过滤器的子查询删除

javascript - 接受可以包含特定集合的字符串+如果包含特定单词则拒绝它

java - 如何在可运行的 jar 中访问我的应用程序资源?

python - Django MPTT 排序

java - 找出二叉树的直径