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
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ classSolution{ /* One step right and then always left */ publicintsuccessor(TreeNode root){ root = root.right; while (root.left != null) root = root.left; return root.val; }
/* One step left and then always right */ publicintpredecessor(TreeNode root){ root = root.left; while (root.right != null) root = root.right; return root.val; }
public TreeNode deleteNode(TreeNode root, int key){ if (root == null) returnnull;
// delete from the right subtree if (key > root.val) root.right = deleteNode(root.right, key); // delete from the left subtree elseif (key < root.val) root.left = deleteNode(root.left, key); // delete the current node else { // the node is a leaf if (root.left == null && root.right == null) root = null; // the node is not a leaf and has a right child elseif (root.right != null) { root.val = successor(root); root.right = deleteNode(root.right, root.val); } // the node is not a leaf, has no right child, and has a left child else { root.val = predecessor(root); root.left = deleteNode(root.left, root.val); } } return root; } }