【问题标题】:BST traversal pre-orderBST遍历预购
【发布时间】:2015-02-08 04:25:58
【问题描述】:

在 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

【问题讨论】:

    标签: algorithm binary-search-tree


    【解决方案1】:

    您使用curr.compareTo(c)&lt;0(意思是“c大于curr”)作为将c放在@的左边的条件987654325@。我不确定你到底想写什么,但这将是完全相反的。 (要么翻转ccurr,要么把&lt;改成&gt;,或者左右互换。)

    【讨论】:

    • 比我快 30 秒...修复应该是这个 if 条件(在插入中)或方法的实现 compareTo()
    • compareTo 代码是:类节点实现 Comparable{ @Override public int compareTo(node aThat) { return this.vaThat.v? 1:0; } }
    猜你喜欢
    • 2017-03-05
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多