Remove Node in Binary Search Tree
ID: 87; hard; 删除二叉查找树的节点
Solution 1 (Java)
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: The root of the binary search tree.
* @param value: Remove the node with given value.
* @return: The root of the binary search tree after removal.
*/
public TreeNode removeNode(TreeNode root, int value) {
if (root == null)
return root;
if (value < root.val) {
root.left = removeNode(root.left, value);
} else if (value > root.val) {
root.right = removeNode(root.right, value);
} else {
if (root.left == null && root.right == null)
return null;
if (root.left == null)
return root.right;
if (root.right == null)
return root.left;
int predecessor = findPred(root.left);
root.val = predecessor;
root.left = removeNode(root.left, predecessor);
}
return root;
}
private int findPred(TreeNode root) {
if (root.right == null)
return root.val;
return findPred(root.right);
}
}Notes
Last updated