zoukankan      html  css  js  c++  java
  • 0450. Delete Node in a BST (M)

    Delete Node in a BST (M)

    题目

    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
    

    题意

    删除二叉搜索树中的一个结点。

    思路

    使用递归实现:

    1. 如果 key<root.val,向左递归;
    2. 如果 key>root.val,向右递归;
    3. 如果 key==root.val,分为3中情况:
      1. root没有左子树,那么直接返回root的右子树;
      2. root没有右子树,那么直接返回root的左子树;
      3. root既有左子树又有右子树,那么在root的右子树中找到最小的值,即右子树中最左侧的结点,将它的值赋给root,再删掉这个结点(即上述没有左子树的情况)。也可以找root左子树中最大(最右侧)的结点。

    代码实现

    Java

    class Solution {
        public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) {
                return null;
            }
    
            if (key < root.val) {
                root.left = deleteNode(root.left, key);
            } else if (key > root.val) {
                root.right = deleteNode(root.right, key);
            } else if (root.left == null) {
                root = root.right;
            } else if (root.right == null) {
                root = root.left;
            } else {
                TreeNode cur = root.right;
                TreeNode pre = root;
                while (cur.left != null) {
                    cur = cur.left;
                    pre = pre == root ? root.right : pre.left;
                }
                root.val = cur.val;
                if (pre == root) {
                    pre.right = cur.right;
                } else {
                    pre.left = cur.right;
                }
            }
    
            return root;
        }
    }
    
  • 相关阅读:
    Ubuntu 16.04 not a com32r image
    重定向输出遇到的缓冲问题
    you don't have permission to access / on this server解决
    LaTeX入门简介
    解决eclipse中出现Resource is out of sync with the file system问题
    Ubuntu安装新英伟达驱动出现问题解决方法
    同步与异步的区别
    Cuda入门笔记
    解决 Cocos2d-x 3.2 error C1041: 无法打开程序数据库vc120.pdb
    vs2013编译过程中,错误 59 error C4996: 'GetVersionExW': 被声明为已否决
  • 原文地址:https://www.cnblogs.com/mapoos/p/13591525.html
Copyright © 2011-2022 走看看