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:
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; } } } }
相关文章推荐
- 450. Delete Node in a BST
- 450. Delete Node in a BST
- LeetCode - 450 - Delete Node in a BST
- LeetCode 450.Delete Node in a BST
- [hard]450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- Delete Node in a BST
- How to delete a node in BST?
- Delete Node in a BST
- 450. Delete Node in a BST
- 450. Delete Node in a BST
- 450. Delete Node in a BST
- Leetcode: Delete Node in a BST
- [leetcode]450. Delete Node in a BST
- [LeetCode]Delete Node in a BST
- 【二叉搜索树:删除指定结点】leetcode 450. Delete Node in a BST
- LeetCode Delete Node in a BST
- 450. Delete Node in a BST
- Leetcode-450. Delete Node in a BST
- [leetCode刷题笔记]450. Delete Node in a BST