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

Remove Node in Binary Search Tree

2015-01-20 05:49 417 查看
This is one of the pretty interesting technical interview questions I see, it is rather fundamental, you probably have seen similar from your text book. But you know what, in the real interview process, few people can actually implement the code correctly,
around 10% graduates from top CS schools, let's put it that way.

The following is my java implementation:

public TreeNode remove(TreeNode root, int target){
if(root==null)
return root;
if(target<root.data)
root.left = remove(root.left,target);
else if(target>root.data)
root.right = remove(root.right,target);
//now we find this node, root.data = target, just need to delete this node
else{
// case 1, root is a leaf node
if(root.left==null && root.right==null)
root = null;
// case 2, root has only left subtree
else if(root.right==null)
root = root.left;
// case 3, root has only right subtree
else if(root.left==null)
root = root.right;
// case 4 root has both left and right subtree
else{
//we can either find the largest value from left subtree or smallest from right subtree
root.data = findSmallest(root.right);
// delete that duplicate node from right sub tree
remove(root.right,root.data);
}

}
return root;
}

public int findSmallest(TreeNode root){
if(root==null) return 0;
if(root.left==null)
return root.data;
else return findSmallest(root.left);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Binary Search Tree