Lintcode: Remove Node in Binary Search Tree

时间:2023-03-08 20:42:26
Lintcode: Remove Node in Binary Search Tree
iven 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.

Have you met this question in a real interview? Yes
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

分析:假设当前node 为root

1. if value < root.val, 要被删除的节点在左子树,往左子树递归,并把操作结束后的返回值作为新的root.left

2. if value > root.val, 要被删除的节点在右子树,往右子树递归, 并把操作结束后的返回值作为新的root.right

3. if root == null, 递归到了一个null点,说明要删的value不存在,return null,而这个null点的parent的相应子树本来也是null,对树的结构没有任何影响

4. if value == root.val,说明root是该被删除的了

  A. if root.left == null, return root.right

  B. if root.right == null, return root.left(这两个case其实包含了只有一个child和一个child都没有的三种情况)

  C. 如果两个children都存在,从右子树中找最小的node,与root交换,再递归调用函数在右子树中删除root.val

 /**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param value: Remove the node with given value.
* @return: The root of the binary search tree after removal.
*/
public TreeNode removeNode(TreeNode root, int value) {
// write your code here
if (root == null) return null;
if (value < root.val)
root.left = removeNode(root.left, value);
else if (value > root.val)
root.right = removeNode(root.right, value);
else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
TreeNode minOfRight = findMin(root.right);
//swap root and minOfRight
int temp = root.val;
root.val = minOfRight.val;
minOfRight.val = temp;
root.right = removeNode(root.right, minOfRight.val);
}
return root;
} public TreeNode findMin(TreeNode cur) {
while (cur.left != null) {
cur = cur.left;
}
return cur;
}
}