zoukankan      html  css  js  c++  java
  • 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
    

    思路:

    注意是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 }
     
  • 相关阅读:
    WPF/Sliverlight ScrollViewer与Panel(2)
    OpenGL学习笔记(7)多边形绘制
    OpenGL学习笔记(10)抗锯齿
    OpenGL学习笔记(9)颜色混合
    GLUT函数说明(转)
    OpenGL学习笔记(8)显示列表
    C#操作IIS的代码
    完整解决Flash载入中文FLASH乱码问题
    用C#的IIS上配置用户账号
    ASP.NET定时调用WebService 运行后台代码
  • 原文地址:https://www.cnblogs.com/zle1992/p/7850482.html
Copyright © 2011-2022 走看看