Java AVL树节点的旋转会导致节点消失
我正试图用Java编写一个AVL树,已经在这上面呆了两个晚上了。当运行下面的代码时,肯定会发生旋转,但例如leftRotate的最终结果是丢失节点Java AVL树节点的旋转会导致节点消失,java,tree,nodes,Java,Tree,Nodes,我正试图用Java编写一个AVL树,已经在这上面呆了两个晚上了。当运行下面的代码时,肯定会发生旋转,但例如leftRotate的最终结果是丢失节点 public AVLNode leftRotate(AVLNode node){ //receives the grandparent node AVLNode temp = node.right; node.right = temp.left; temp.left = node; return temp;
public AVLNode leftRotate(AVLNode node){ //receives the grandparent node
AVLNode temp = node.right;
node.right = temp.left;
temp.left = node;
return temp;
}
public AVLNode rightRotate(AVLNode node){
AVLNode temp = node.left;
node.left = temp.right;
temp.right = node;
return temp;
}
public AVLNode rightLeftRotate(AVLNode node){
node.right = rightRotate(node.right);
return leftRotate(node);
}
public AVLNode leftRightRotate(AVLNode node){
node.left = leftRotate(node.left);
return rightRotate(node);
}
如果我将root=temp
添加到左旋转和右旋转方法中,则旋转和新显示仅在第一次循环中成功发生,然后所有内容都会混淆
示例:插入4、5和6。旋转后,temp
保持5为其值
“根”,正确包含4和6作为其左右子级的键。但是,在方法结束后,所有这些都消失了,我的树的根的左、右子级现在都为null
我知道我错过了一些小东西,但我不能把我的头绕在它周围
我还知道它不是我的
addNode
函数,因为当它添加完所有节点后,生成的树就是一个二叉搜索树。只有在调用这些函数时,我才开始丢失节点。有什么帮助吗?我认为问题在于如何管理内存,而不是AVLNode temp=node.left;或AVLNode temp=node.left代码>实例化一个新的AVLNode并复制信息,这样就不会有指向上一个对象的指针。
当您执行AVLNode temp=node.left;temp是指向node.left的指针,因此如果返回temp,所有更改和旋转都将对原始节点执行