繁体   English   中英

用Java递归创建二进制搜索树

[英]Creating a Binary Search Tree recursively in Java

我一直在尝试创建将创建完整的二进制搜索树的递归方法。 此方法返回对该树的根的引用。 作为参数,我传递树的深度以及存储在当前子树根目录中的数字。 当深度为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

当空树由null表示时,通常不需要多个基本情况。

public class BinaryNode {
    public static BinaryNode bstFactory( int data, int depth ) {
        if ( depth >= 31 )
            throw new IllegalArgumentException( "too deep for integer data" );
        else if ( depth < 0 )
            throw new IllegalArgumentException( "non-sensical depth" );
        return ( depth == 0 )
            ? null
            : new BinaryNode(
                data,
                bstFactory( data - ( 1 << depth ), depth - 1 ),
                bstFactory( data + ( 1 << depth ), depth - 1 )
            );
    }
    BinaryNode( int data, BinaryNode left, BinaryNode right ) { /*...*/ }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM