解题思路
- 这道题采用前序遍历和后序遍历均可,需要搜索整个树,本算法使用后序遍历。
- 此树为二叉搜索树,搜索树节点的左子树均小于该节点,右子树均大于该节点。因此roo.val < key 遍历右子树, 反之左子树。
- 删除节点需要以下三种情况
- 该节点为叶子节点,返回null即可
- 该节点的左子节点不为空,右子节点为空,返回其左子节点。反之返回右子节点。
- 该节点左右节点均不为空,则将该节点的左子树作为该节点其右子树最左节点的左子树,返回该节点右子节点。
- 删除该节点的做法就是直接将该节点的父母节点指向该节点的左/右节点。
具体代码
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return root;
if(root.val > key) root.left = deleteNode(root.left, key);
if(root.val < key) root.right = deleteNode(root.right, key);
if(root.val == key){
if(root.left == null && root.right != null) return root.right;
else if(root.left != null && root.right == null) return root.left;
else if(root.left != null && root.right != null){
TreeNode temp = root.right;
while(temp.left != null) temp = temp.left;
temp.left = root.left;
return root.right;
}else{
return null;
}
}
return root;
}