为什么只创建二叉树的右节点?

Why only right nodes of binary tree are created?

我应该创建一个接受整数数组的二叉搜索树。我想知道如何访问节点class中的左右节点来创建左右节点。

但是,这段代码只创建了二叉树的右节点。我的代码有什么问题?

这是节点 class:

private int element;
private BinaryNode left;
private BinaryNode right;

public Node( ){
    this( 0, null, null );
}

public( int theElement, BinaryNode lt, BinaryNode rt ){
    element = theElement;
    left    = lt;
    right   = rt;
}

public int getElement( ){
    return element;
}

public BinaryNode getLeft( ){
    return left;
}

public BinaryNode getRight( ){
    return right;
}

public void setElement( int x ){
    element = x;
}

public void setLeft( BinaryNode t ){
    left = t;
}

public void setRight( BinaryNode t ){
    right = t;
}

这是我创建树的代码。这两个代码块在不同的 java class 文件中:

static Node obj = new Node();
static Node root = new Node();

static Node BinaryTree(int[] array, int begin, int end){
    if(begin > end){  //checks in the array is still in bound
        return null;  //returns null so the next node can be null
    }

    int middle = (begin + end)/2;  //finds the middle index
    obj.setElement(array[middle]);
    root = new Node(obj.getElement(), obj.getLeft(), obj.getRight()); //creates the root node of the tree/subtree
    root.setLeft(BinaryTree(array, begin, middle-1)); //creates the left tree or node recursively
    root.setRight(BinaryTree(array, middle+1, end));  //creates the right tree or node recursively
    return root; //places/returns the node of the tree in its place
}

一些问题是:

  • 您的代码混合了 BinaryNodeNode。我假设 Node.
  • 第一个代码块的构造函数没有名称 -- 这是一个语法错误。
  • root 不应初始化为 new Node,而应初始化为调用 BinaryTree
  • 的 return 值
  • obj 不应在大于 BinaryTree 函数的范围内定义,因为您将不断重复使用 same 对象在每次递归调用中,这将对算法产生破坏性影响。你甚至不需要这个变量。

BinaryTree改为:

static Node BinaryTree(int[] array, int begin, int end){
    if (begin > end) {
        return null;
    }

    int middle = (begin + end) / 2;
    return new Node(array[middle], BinaryTree(array, begin, middle - 1), 
                                   BinaryTree(array, middle + 1, end));
}

一个示例调用可能是这样的:

int[] array = {1,2,3,4,5};
Node root = BinaryTree(array, 0, array.length - 1);