为什么在这种情况下我尝试删除的Treenode不会被删除?

时间:2016-12-27 05:18:08

标签: c++

我写了一个函数来删除一个节点,其值等于BST中的给定键,我尝试了一个简单的例子[5,3,6],并删除了key = 3.但是当我运行这段代码时,3不是删除。此代码的输出: root = 5 left = 3 right = 6 为什么?谢谢!

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

// delete key in the tree
TreeNode* deleteNode(TreeNode* root, int key) {
    TreeNode* cur = root;
    // find the node to delete
    while(cur) {
        if(cur->val == key) break;
        if(cur->val > key) cur = cur->left;
        else cur = cur->right;
    }
    if(!cur) return root;
    // I want to delete the node of val 3 here
    // here cur == root->left, I though when I do cur = 0, root->left will also be set to 0
    if(!cur->left && !cur->right) {
        assert(cur == root->left);
        delete cur;
        cur = 0;
    }
    if(root) cout << "root = " << root->val << endl;
    // but root->left is not nullptr when I ran this, and 3 still exists
    if(root->left) cout << "left = " << root->left->val << endl;
    if(root->right) cout << "right = " << root->right->val << endl;
    return root;
}

int main() {
    TreeNode* root = new TreeNode(5);
    TreeNode* l = new TreeNode(3);
    TreeNode* r = new TreeNode(6);
    root->left = l;
    root->right = r;
    deleteNode(root, 3);
}

2 个答案:

答案 0 :(得分:2)

问题是你有一个悬空指针。您需要在&#34; parent&#34;中设置left节点到NULL。同样,如果您删除了右侧的节点,则需要将父right指针设置为NULL

答案 1 :(得分:1)

root->left不是空指针,因为您从未将其设置为NULL。您将cur设置为NULL。因此,您继续取消引用已删除的指针,这是未定义的行为。在您的情况下,先前为左节点分配的内存保持不变,并且在您查询时仍然存在。