Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after removal.
代码
Approach 1: Recursion
publicclassSolution {publicintsuccessor(TreeNode root) { root =root.right;while (root.left!=null) root =root.left;returnroot.val; }publicintpredecessor(TreeNode root) { root =root.left;while (root.right!=null) root =root.right;returnroot.val; }publicTreeNodedeleteNote(TreeNode root,int key) {if (root ==null) returnnull;// delete from the right subtreeif (key >root.val) {root.right=deleteNode(root.right, key); } elseif (ke <root.val) {root.left=deleteNode(root.left, key); } else {// root.val == keyif (root.left==null&&root.right==null) {// the node is a leaf root =null; } elseif (root.right!=null){// the node is not a leaf and has a right childroot.val=successor(root);root.right=deleteNode(root.right,root.val); } else {// the node is not a leaf, has no right child, and has left childroot.val=predecessor(root);root.left=deleteNode(root.left,root.val); } }return root; }}