• [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 }
  • 相关阅读:
    jQuery 字符串拼接
    jQuery 筛选器 链式编程操作
    jQuery 常用操作
    jQuery介绍 常用选择器
    枚举-增加BOOL类型
    枚举-判断一年中第 125 天是工作日, 还是休息日?假设一年 365 天, 新年第一天是星期一。
    判断大小端序
    信息存储,共用体的应用
    栈的自实现
    strlen,strcat,strcpy,strcpm 自实现
  • 原文地址:https://www.cnblogs.com/David-Lin/p/7786557.html
Copyright © 2020-2023  润新知