450. Delete Node in a BST
2017-03-03 10:44
260 查看
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
递归的思想,如果当前节点的值>target就在左子树里递归,<target就在右子树里递归。
如果要删除当前节点的话又分两种情况:
1、当前节点左子树或右子树为空:直接将不为空的一边赋给当前节点就好。
2、找到当前右子树的最小值赋给当前节点,递归删除右子树中的最小值节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root) return NULL;
if(root->val>key) root->left=deleteNode(root->left, key);
else if(root->val<key) root->right=deleteNode(root->right, key);
else{
if(!root->left||!root->right) root=!(root->left)?root->right:root->left;
else{
auto rightMin=root->right;
while(rightMin->left) rightMin=rightMin->left;
root->val=rightMin->val;
root->right=deleteNode(root->right, rightMin->val);
}
}
return root;
}
};
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
递归的思想,如果当前节点的值>target就在左子树里递归,<target就在右子树里递归。
如果要删除当前节点的话又分两种情况:
1、当前节点左子树或右子树为空:直接将不为空的一边赋给当前节点就好。
2、找到当前右子树的最小值赋给当前节点,递归删除右子树中的最小值节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root) return NULL;
if(root->val>key) root->left=deleteNode(root->left, key);
else if(root->val<key) root->right=deleteNode(root->right, key);
else{
if(!root->left||!root->right) root=!(root->left)?root->right:root->left;
else{
auto rightMin=root->right;
while(rightMin->left) rightMin=rightMin->left;
root->val=rightMin->val;
root->right=deleteNode(root->right, rightMin->val);
}
}
return root;
}
};
相关文章推荐
- LeetCode 450.Delete Node in a BST
- 450. Delete Node in a BST
- [hard]450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- [leetcode]450. Delete Node in a BST
- 【二叉搜索树:删除指定结点】leetcode 450. Delete Node in a BST
- [leetCode刷题笔记]450. Delete Node in a BST
- 450. Delete Node in a BST
- Leetcode-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 (Medium) (cpp)
- leetcode 450. Delete Node in a BST
- leetcode 450. Delete Node in a BST
- 450. Delete Node in a BST
- LeetCode "450. Delete Node in a BST"
- 450. Delete Node in a BST**
- 450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- 450. Delete Node in BST