插入红黑树时出现空指针异常

时间:2014-09-14 19:30:22

标签: java red-black-tree

我正在尝试将一长串单词插入红黑树。我的插入功能似乎如下工作。当我通过这个调试时,在注释insertFix(iter);时,它会完美地构建红黑树。

private TreeNode insert(TreeNode iter, TreeNode parent, String item) {
    if (iter == null) {
        iter = new TreeNode(item, null, parent, null, RED);
    } else {
        if (item.compareTo(iter.item) < 0) {
            iter.left = insert(iter.left, iter, item);
        } else {
            iter.right = insert(iter.right, iter, item);
        }
    }

    insertFix(iter);
    return(iter);
}

然而,我无法弄清楚红黑树的insertFix()部分。我一直在下面的代码中获得各种空指针异常。例如,在while循环的开始,我得到一个空指针异常,当我添加一个像iter.parent.parent != null这样的子句时,我最终在另一个部分得到一个新的空指针异常。这次是在if语句tmp.color == red

private void insertFix(TreeNode iter) {
    TreeNode tmp;
    while (iter.parent.color == RED) {
        if (iter.parent == iter.parent.parent.left) {
            tmp = iter.parent.parent.right;
            if (tmp.color == RED) {
                iter.parent.color = BLACK;
                tmp.color = BLACK;
                iter.parent.parent.color = RED;
                iter = iter.parent.parent;
            } else if (iter == iter.parent.right) {
                iter = iter.parent;
                leftRotate(iter);
            } else {
                iter.parent.color = BLACK;
                iter.parent.parent.color = RED;
                rightRotate(iter);
            }
        } else {
            tmp = iter.parent.parent.left;
            if (tmp.color == RED) {
                iter.parent.color = BLACK;
                tmp.color = BLACK;
                iter.parent.parent.color = RED;
                iter = iter.parent.parent;
            } else if (iter == iter.parent.left) {
                iter = iter.parent;
                rightRotate(iter);
            } else {
                iter.parent.color = BLACK;
                iter.parent.parent.color = RED;
                leftRotate(iter);
            }
        }
    }
    root.color = BLACK;
}

我完全错过了什么吗?如果是这样,有人可以指出我正确的方向。另外,我的TreeNode类构建如下:

private class TreeNode {
    String item;
    TreeNode left;
    TreeNode right;
    TreeNode parent;
    int color;

    TreeNode(String item, TreeNode left, TreeNode parent, TreeNode right, int color) {
        this.item = item;
        this.left = left;
        this.parent = parent;
        this.right = right;
        this.color = color;
    }
}

这就是我调用上面代码的方式:

public void insert(String item) {
    root = insert(root, root, item);
}

0 个答案:

没有答案