如何解决AVL Java 插入和删除递归溢出错误
在 AVL 树中插入/删除节点时出现此溢出错误。我需要插入大约 1000-3000 个元素。
AVL 插入
//Insert number into AVL
public static void insert(int num) {
AVLNode newNode = new AVLNode(num);
root = insertAVL(root,newNode);
noOfNodes++;
}
public static AVLNode insertAVL(AVLNode parent,AVLNode newNode) {
if (parent == null) {
return newNode;
}
if (newNode.num < parent.num) {
comparisons++;
parent.left = insertAVL(parent.left,newNode);
} else if (newNode.num > parent.num) {
comparisons++;
parent.right = insertAVL(parent.right,newNode);
} else {
return newNode;
}
// Adjust height of parent node
parent.height = 1 + max(parent.left,parent.right);
// Get Balance Factor
int balanceFac = getBalance(parent);
// Left Left
if (balanceFac > 1 && newNode.num < parent.left.num) {
totalRot++;
return rightRot(parent);
}
// Right Right
if (balanceFac < -1 && newNode.num > parent.right.num) {
totalRot++;
return leftRot(parent);
}
//Right Left
if (balanceFac < -1 && newNode.num < parent.right.num) {
parent.right = rightRot(parent.right);
totalRot += 2;
return leftRot(parent);
}
// Left Right
if (balanceFac > 1 && newNode.num > parent.left.num) {
parent.left = leftRot(parent.left);
totalRot += 2;
return rightRot(parent);
}
// If no rotation is needed return parent
return parent;
}
AVL 删除中的错误与插入中的错误类似。尝试递归存储左右节点时发生错误: parent.left = ... 或 parent.right = ...
代码可以处理大约 20 个元素。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。