algorithm - BST遍历预序

标签 algorithm binary-search-tree

在 BST 前序遍历中,我没有看到预期的结果。
请帮助确认这是代码问题还是我对预序遍历如何工作的理解。

节点:

class node implements Comparable<node>{
        int v;
        node left;
        node right;
        node(int v){ this.v=v;}
        boolean equals(node o){
            return(this.v==o.v);
        }
        @Override public int compareTo(node aThat) {
            return this.v<aThat.v?-1:this.v>aThat.v?1:0;
        }
        public String toString(){ return "->" + this.v;}
    }

插入代码 -

public binarySearch(int r){
        Random rnd=new Random();
        int[] val=new int[r];
        for(int i=0;i<r;i++){
            val[i]=rnd.nextInt(50);
        }
        System.out.println("Array -> " + Arrays.toString(val));
        root=new node(val[0]);
        for(int i=1;i<val.length-1;i++){
            insert(root,new node(val[i]));
        }
    }

插入(构建)代码 -

private void insert(node curr,node c){
    if(curr==c){ return;}
    if(curr.compareTo(c)<0)
    {
        if(curr.left==null){curr.left=c; return;}
        insert(curr.left,c);
    }
    else
    {
        if(curr.right==null){curr.right=c; return;}
        insert(curr.right,c);
    }
}

遍历代码(预购)-

private void print(node c){
        if(c==null) return;
        System.out.println(c);
        print(c.left);
        print(c.right);

    }

输入数组 -

 [22, 17, 24, 11, 5, 9, 25]

预期(?) -

 ->22 ->17 ->11 ->5 ->9 ->24

输出-

 ->22 ->24 ->17 ->11 ->5 ->9

最佳答案

您正在使用 curr.compareTo(c)<0 (意思是“c 大于 curr ”)作为放置 c 的条件在 curr左边 .我不确定你到底想写什么,但它恰恰与此相反。 (翻转 ccurr ,或将 < 更改为 > ,或左右交换。)

关于algorithm - BST遍历预序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28390552/

相关文章:

algorithm - 最大值计数

c++ - 在另一个类中使用一个类对象

python - 将 ruby​​ 翻译成 python

java - 解码字符串有多少种方法?

binary-tree - 什么是有效的二叉搜索树?

php - 二叉搜索树后序迭代器

algorithm - 计算二叉搜索树中节点的等级

c++ - 如何在二叉搜索树节点中找到次要元素的平均值

c - 给定限制生成集合的所有子集

algorithm - 无法理解 8-N 难题