Problem
Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after removal.
Example
Given binary search tree:
5
/ \
3 6
/ \
2 4
Remove 3, you can either return:
5
/ \
2 6
\
4
or
5
/ \
4 6
/
2
Note
以下是rebuild的示意:先让r
到达r
的最左端,然后将l
接在r
的左子树,这样就把所有比root.left
大的结点都集合在root.right
了。将root.right
接在root.left
的右子树,然后返回root.left
即可。
(1)
root
/ \
left right
/ \ / \
x l r x
(2)
left right
/ \ / \
x r x
/
l
(3)
left
/ \
x right
/ \
r x
/
l
Solution
public class Solution {
public TreeNode removeNode(TreeNode root, int value) {
TreeNode dummy = new TreeNode (-1), pre = dummy, cur = root;
dummy.right = root;
while (cur != null) {
if (cur.val == value) {
if(pre.left == cur) {
pre.left = makenew(cur);
}
else pre.right = makenew(cur);
break;
}
else if (cur.val < value) {
pre = cur;
cur = cur.right;
}
else {
pre = cur;
cur = cur.left;
}
}
return dummy.right;
}
private TreeNode makenew(TreeNode node) {
if (node.left == null || node.right == null) {
return node.left == null ? node.right : node.left;
}
TreeNode left = node.left.right;
TreeNode right = node.right.left;
while (right.left != null) {
right = right.left;
}
right.left = left;
node.left.right = node.right;
return node.left;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。