Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
- Search for a node to remove.
- If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
Example:
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
思路:
注意是BST 已经排好序了。
找到要删除的node;
node 不含左右节点 返回null;
node 只含有左子树,返回左子树
node只含有右子树,返回右子树
node 左右子树都有,找到右子树种最下的值,赋给node,递归地删掉 有字数中最小的元素
1 class Solution { 2 public TreeNode deleteNode(TreeNode root, int key) { 3 if(root==null) return null ; 4 if(root.val>key) root.left=deleteNode(root.left,key); 5 else if(root.val<key) root.right = deleteNode(root.right,key); 6 else { 7 8 if(root.left==null) return root.right; 9 if(root.right==null) return root.left; 10 11 TreeNode rightmin = findmin(root.right); 12 root.val = rightmin.val; 13 root.right = deleteNode(root.right,root.val); 14 } 15 return root; 16 } 17 private TreeNode findmin(TreeNode root){ 18 while(root.left!=null) 19 root=root.left; 20 return root; 21 } 22 23 24 }