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 (将#修改为@)