您的位置:首页 > Web前端 > Node.js

leetcode 450. Delete Node in a BST

2017-05-31 23:21 459 查看
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]
key = 3

5
/ \
3   6
/ \   \
2   4   7

Given key to delete is 3. So we find the node with value 3 and delete it.

One valid answer is [5,4,6,2,null,null,7], shown in the following BST.

5
/ \
4   6
/     \
2       7

Another valid answer is [5,2,6,null,4,null,7].

5
/ \
2   6
\   \
4   7


关键是定义子树上升的方式

可以选择将要删除点的右孩子上升,替代要删除的点。

然后将该右孩子的左子树加到要删除点的左子数的最右方。

一个不优美的解法,之后再完善

public class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root==null) return null;
if(root.val==key) return upFlow(root, root.right);

TreeNode pre, p;
pre = root;
p = root;
//find the position
while(p!=null && p.val!=key){
if(p.val > key){
pre = p;
p = p.left;
}else{
pre = p;
p = p.right;
}
}

if(p==null) return root;
if(pre.left == p){
pre.left = upFlow(p, p.right);
}else{
pre.right = upFlow(p, p.right);
}
return root;
}

public TreeNode upFlow(TreeNode pre, TreeNode target){
if(target==null) return pre.left;
if(pre.left==null) return target;
TreeNode left = target.left;
target.left = pre.left;
TreeNode p = pre.left;

while(p.right!=null){
p = p.right;
}
p.right = left;
return target;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode