Question: delete the given value in BST.
This question is pretty tricky, to delete a node in BST, there are several cases to consider.
1: The node is one of the leaves, 2: the node only has right children, 3: the node only has left children, 4: the node has left and right children.
code:
TreeNode* deleteTreeNode(TreeNode* root, int val) {
if(!root) return NULL;
else {
if(val < root->val) root->left = deleteTreeNode(root->left, val);
else if(val > root->val) root->right = deleteTreeNode(root->right, val);
else {
// if there is no left child, no right child
if(root->left == NULL && root->right == NULL) {
delete root;
root = NULL;
return root;
}
else if(root->left == NULL) { // if there is no left subtree
TreeNode* tmp = root;
root = root->right;
delete tmp;
return root;
} else if(root->right == NULL) { // if there is no right subtree
TreeNode* tmp = root;
root = root->right;
delete tmp;
return root;
} else { // two children
struct TreeNode* tmp = findMin(root->right);
root->data = tmp->data;
root->right = deleteTreeNode(root->right, tmp->data);
return root;
}
}
}
}
本文探讨了二叉搜索树(BST)中删除特定值的节点这一复杂问题。文章详细阐述了四种不同情况:叶子节点、仅有右子树的节点、仅有左子树的节点以及同时拥有左右子树的节点。通过递归函数实现,并提供了完整的C++代码示例。
359

被折叠的 条评论
为什么被折叠?



