[Leetcode]450. Delete Node in a BST

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:

  1. Search for a node to remove.
  2. 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


思路:分两种情况,一种是要删除的节点只有一个孩子,另一种是要删除的节点有两个孩子;
如果只有一个孩子,那么我们让这个节点引用到他非空的孩子上去,即root = root.right或
root = root.left;如果有两个孩子的话,那么有两种办法,一种是找他右边的最小值,另一种
是找他左边的的最大值。将值赋给该节点,然后删除右边最小值或左边最大值;

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public TreeNode deleteNode(TreeNode root, int key) {
12         if (root==null)
13             return null;
14         else if (key<root.val)
15             root.left = deleteNode(root.left,key);
16         else if (key>root.val)
17             root.right = deleteNode(root.right,key);
18         else {
19             if (root.left!=null&&root.right!=null){
20                 TreeNode tmp = findMin(root.right);
21                 root.val = tmp.val;
22                 root.right = deleteNode(root.right,root.val);
23             }
24             else {
25                 TreeNode tmp = root;
26                 if (root.left==null)
27                     root = root.right;
28                 else if (root.right==null)
29                     root = root.left;
30                 tmp = null;
31             }
32         }
33         return root;
34     }
35     private TreeNode findMin(TreeNode root){
36         if (root==null)
37             return null;
38         if (root.left==null)
39             return root;
40         return findMin(root.left);
41     }
42 }

 

posted @ 2017-11-05 09:29  SkyMelody  阅读(97)  评论(0编辑  收藏  举报