[英]Why only right nodes of binary tree are created?
I'm supposed to create a binary search tree that takes in an integer array.我应该创建一个包含 integer 数组的二叉搜索树。 I want to know how can I access the left and right nodes in the Node class to create the left and right nodes.
我想知道如何访问Node class中的左右节点来创建左右节点。
However, this code only creates the right nodes of the binary tree.但是,此代码仅创建二叉树的正确节点。 What is wrong with my code?
我的代码有什么问题?
This is the Node 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;
}
And this is my code to create the tree.这是我创建树的代码。 These two blocks of code are in different java class files:
这两个代码块位于不同的 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
}
Some of the issues are:其中一些问题是:
BinaryNode
and Node
.BinaryNode
和Node
。 I will assume Node
.Node
。root
should not be initialised as new Node
, but as the return value from a call to BinaryTree
root
不应初始化为new Node
,而是作为调用BinaryTree
的返回值obj
should not be defined in a scope that is larger than the BinaryTree
function, as you will keep reusing the same object over and over in each recursive call, which will have devastating effects on the algorithm. obj
不应在大于 BinaryTree BinaryTree
的 scope 中定义,因为您将继续重复使用相同的 object,这将在每个算法中一遍又一遍地产生破坏性影响。 You don't even need this variable. Change BinaryTree
to this:将
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));
}
An example call could be like this:一个示例调用可能是这样的:
int[] array = {1,2,3,4,5};
Node root = BinaryTree(array, 0, array.length - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.