450. Delete Node in a BST
/**
* 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==NULL) 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->right || !root->left) root = (root->left?root->left:root->right);
else
{
TreeNode *cur = root->right;
while(cur->left) cur=cur->left;
root->val = cur->val;
root->right = deleteNode(root->right,cur->val);
}
}
return root;
}
};
适用于一般二叉树的方法:
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) return NULL;
if (root->val == key) {
if (!root->right || !root->left) return root->left?root->left:root->right;
else {
TreeNode *cur = root->right;
while (cur->left) cur = cur->left;
swap(root->val, cur->val);
}
}
root->left = deleteNode(root->left, key);
root->right = deleteNode(root->right, key);
return root;
}
};