450. Delete Node in a BST
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
方法1:
huahua: https://www.youtube.com/watch?v=00r9qf7lgAk
grandyang:http://www.cnblogs.com/grandyang/p/6228252.html
思路:
首先根据BST的性质左右递归找到要删除的节点。如果找到了这个a,要分为四种情况讨论:1. a是叶节点,直接变成nullptr,2. a只有左子树,把a的左子树attach到a的父节点上,3. a只有右子树,把a的右子树attach到a的父节点上。4. a同时存在左右子树:需要找到a在右子树中的successor,来替代a的位置。具体做法是将这个successor的值赋给root,然后递归在右子树中删除这个successor。或者swap。
易错点
Complexity
Time complexity: O(h)
Space complexity: O(h)
/**
* 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 nullptr;
if (root -> val < key) root -> right = deleteNode(root -> right, key);
else if (root -> val > key) root -> left = deleteNode(root -> left, key);
else {
if (!root -> left) {
root = root -> right;
}
else if (!root -> right) {
root = root -> left;
}
else {
TreeNode* cur = root -> right;
while (cur -> left) cur = cur -> left;
root -> val = cur -> val;
root -> right = deleteNode(root -> right, cur -> val);
}
}
return root;
}
};
方法2: iterative
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode *cur = root, *pre = NULL;
while (cur) {
if (cur->val == key) break;
pre = cur;
if (cur->val > key) cur = cur->left;
else cur = cur->right;
}
if (!cur) return root;
if (!pre) return del(cur);
if (pre->left && pre->left->val == key) pre->left = del(cur);
else pre->right = del(cur);
return root;
}
TreeNode* del(TreeNode* node) {
if (!node->left && !node->right) return NULL;
if (!node->left || !node->right) {
return (node->left) ? node->left : node->right;
}
TreeNode *pre = node, *cur = node->right;
while (cur->left) {
pre = cur;
cur = cur->left;
}
node->val = cur->val;
(pre == node ? node->right : pre->left) = cur->right;
return node;
}
};