如何解决为什么只创建二叉树的右节点?
我应该创建一个接受整数数组的二叉搜索树。我想知道如何访问Node类中的左右节点来创建左右节点。
然而,这段代码只创建了二叉树的正确节点。我的代码有什么问题?
这是节点类:
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;
}
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
}
解决方法
一些问题是:
- 您的代码混合了
BinaryNode
和Node
。我假设Node
。 - 第一个代码块有一个没有名字的构造函数——这是一个语法错误。
-
root
不应初始化为new Node
,而应初始化为BinaryTree
调用的返回值 -
obj
不应定义在大于BinaryTree
函数的范围内,因为您将在每次递归调用中一遍又一遍地重复使用 相同 对象,这将对算法产生毁灭性的影响。你甚至不需要这个变量。
将 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),middle + 1,end));
}
一个示例调用可能是这样的:
int[] array = {1,2,3,4,5};
Node root = BinaryTree(array,array.length - 1);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。