您的位置:首页 > Web前端 > Node.js

Delete node in BST

2016-08-06 07:04 337 查看
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;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: