二叉树删除节点功能不起作用

时间:2017-03-31 19:52:46

标签: java algorithm data-structures

public void removeNode(int data) {
    deleteNode(root, data);
}

public Node deleteNode(Node focus, int data) {
    if(focus == null) {
        System.out.println("Tree empty");
        return null;
    }
    else if(data < focus.data) {
        deleteNode(focus.leftchild, data);
    }
    else if(data > focus.data) {
        deleteNode(focus.rightchild, data);
    }
    else {
        // No child
        if(focus.leftchild == null && focus.rightchild == null) {
            focus = null;
        }
        // one child
        else if(focus.leftchild == null) {
            focus = focus.rightchild;
            System.out.println("here");
        }
        else if(focus.rightchild == null) {
            focus = focus.leftchild;
        }
        // 2 children
        else {
            Node temp = findMin(focus.rightchild);
            focus.data = temp.data;
            deleteNode(focus.rightchild, temp.data);
        }
    }
    return focus;
}

public Node findMin(Node focus) {
    while(focus.leftchild != null) {
        focus = focus.leftchild;
    }
    return focus;
}

我已经编写了上面的代码来删除二进制搜索树中的节点。但是由于某种原因,当我运行preordertraversal函数来打印所有节点时,我看到该节点没有被删除。有人可以告诉我为什么节点没有被删除。功能似乎是正确的。

1 个答案:

答案 0 :(得分:0)

我知道了!问题是我没有以正确的方式穿越树。在有两个孩子的情况下我也犯了一个错误。我没有设置正确的焦点。这是更新的代码

public Node deleteNode(Node focus, int data) {
    if(focus == null) {
        System.out.println("Tree empty");
        return null;
    }
    else if(data < focus.data) {
        focus.leftchild = deleteNode(focus.leftchild, data);
    }
    else if(data > focus.data) {
        focus.rightchild = deleteNode(focus.rightchild, data);
    }
    else {
        // No child
        if(focus.leftchild == null && focus.rightchild == null) {
            focus = null;
        }
        // one child
        else if(focus.leftchild == null) {
            focus = focus.rightchild;
            System.out.println("here");
        }
        else if(focus.rightchild == null) {
            focus = focus.leftchild;
        }
        // 2 children
        else {
            Node temp = findMin(focus.rightchild);
            focus.data = temp.data;
            focus.rightchild = deleteNode(focus.rightchild, temp.data);
        }
    }
    return focus;
}