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);
}

本文介绍了一种Java实现二叉树节点删除的方法,包括四种情况:节点为叶子节点、只有一侧子节点、两侧都有子节点,以及如何在特定节点被删除后找到并替换它的值。

1897

被折叠的 条评论
为什么被折叠?



