0
在BST預購遍歷中,我看不到我期望的結果。
請幫助確認這是代碼問題還是我對預序遍歷如何工作的理解。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
比我快30秒......修正應該是這個「if」條件(在插入中)或者在實現中該方法的'的compareTo()' – alfasin 2015-02-08 04:51:06
的compareTo代碼是:類節點實現可比 { \t \t @覆蓋公共INT的compareTo(節點aThat){ \t \t \t返回this.v aThat.v?1:0; \t \t} } –
IUnknown
2015-02-08 05:11:13