完全な二分探索木を作成する再帰的な方法を作成しようとしています。このメソッドは、このツリーのルートへの参照を返します。パラメータとして、ツリーの深さと現在のサブツリーのルートに格納されている数を渡します。深さが 0 と 1 の場合、2 つの基本的なケースの解決策を実行できましたが、1 より大きい数値で試してみると、レベル 0 とレベル 1 のみが正しくインスタンス化され、次のものはインスタンス化されません。どんな助けでも素晴らしいでしょう
public class BinaryNode {
private int data;
private BinaryNode left, right;
public BinaryNode(int initialData, BinaryNode initialLeft,
BinaryNode initialRight) {
data = initialData;
left = initialLeft;
right = initialRight;
}
public static BinaryNode BSTFactory(int top,int depth) {
BinaryNode root=new BinaryNode(top,null,null);
BinaryNode leftChild,rightChild;
if(depth==0)
//return root;
if(depth==1){
//create 2 children left and right
leftChild=new BinaryNode(top-1,null,null);
rightChild=new BinaryNode(top+1,null,null);
root=new BinaryNode(top,leftChild,rightChild);
//return root;
}
if(depth>1){
leftChild=BSTFactory(top-1,depth-1);
rightChild=BSTFactory(top+1,depth-1);
root=new BinaryNode(top,leftChild,rightChild);
//return root;
}
return root;
}
public class Applications {
public static void main(String[] args){
BinaryNode root2=BinaryNode.BSTFactory(8, 2);
System.out.println(root2.toString());
}
}
This is the output:
data: 8
8's left: data: 7
7's left: null
7's right: null
8's right: data: 9
9's left: null
9's right: null