[LintCode] Remove Node in Binary Search Tree [理解BST]

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值