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

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