我寫了一個函數來刪除一個BST的值等於給定鍵的節點,我試了一個簡單的例子[5,3,6],並刪除了鍵= 3。但是當我運行這個代碼時,3沒有被刪除。此代碼的輸出: root = 5 left = 3 right = 6 爲什麼?謝謝!爲什麼在這種情況下,Treenode I嘗試刪除不會被刪除?
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);
}
你能舉一個你的代碼的例子嗎? –