該方法假定需要兩個參數一個用於深度,另一個用於樹的根的整數值。例如:對於任何給定的N,返回深度爲N的完整二分搜索樹的根引用,使得節點存儲整數1,2,...,2 N + 1 - 1。我努力做到這一點。這裏是我的:通過Java方法遞歸生成一個完整的二叉樹
public static BinaryNode BSTFactory(int top,int depth) {
BinaryNode root=new BinaryNode(null,null,top);
BinaryNode leftChild,rightChild;
if(depth==0){
return root;
}
if(depth==1){
//create 2 children left and right
leftChild=new BinaryNode(null,null,top-1);
rightChild=new BinaryNode(null,null,top+1);
root=new BinaryNode(rightChild,leftChild,top);
return root;
}
if(depth>1){
leftChild=BSTFactory(top-1,depth-1);
rightChild=BSTFactory(top+1,depth-1);
root=new BinaryNode(rightChild,leftChild,top);
return root;
}
return root;
}
會發生什麼情況?你能指望什麼? – StilesCrisis 2014-10-29 18:49:43
該方法適用於深度爲0和1的2個基本情況,但對於任何更大的情況它都不起作用。我一定會把事情搞亂,但我似乎無法弄清楚它是什麼。 – sudoMan13 2014-10-29 19:00:10
你知道如何使用調試器嗎?您需要簡單地瀏覽代碼並觀察發生的情況。 – StilesCrisis 2014-10-29 19:13:48