二进制搜索树删除有一个孩子的节点

时间:2012-11-02 02:09:16

标签: binary-search-tree

我有一个二叉搜索树,当我尝试删除具有单个子节点的节点时,您删除该节点并将子节点移动到其中。我有它的代码,但每当我这样做时它会给我一个坏指针。

这是代码的片段

else if((root->Left != NULL) != (root->Right != NULL)){ //Checks if it's a on child node
    if(root->Left != NULL){ //If it has a left child, attempts to move the left child to existing node
        delete root;
        root = root->Left;
    }
    else{ //If it is right child, attempts to move right child to existing node
        delete root;
        root = root->Right;
    }
}

结构具有值

DATA_TYPE Value;
TreeNode* Left;
TreeNode* Right;

我知道我从调试器中分配错了,那么移动节点的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

编辑:

不知道我是如何错过它的,但你在删除它后立即使用root

EDIT2: 你需要一个临时的。

TreeNode* temp = root->Right;
delete root;
root = temp;

答案 1 :(得分:0)

这是方法

的Java实现
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
    if (request.type == "closeTab") {
        chrome.tabs.remove(sender.tab.id);
    }
}
);