zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 450 删除二叉搜索树中的节点

    450. 删除二叉搜索树中的节点

    给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。

    一般来说,删除节点可分为两个步骤:

    首先找到需要删除的节点;
    如果找到了,删除它。
    说明: 要求算法时间复杂度为 O(h),h 为树的高度。

    示例:

    root = [5,3,6,2,4,null,7]
    key = 3

        5
       / 
      3   6
     /    
    2   4   7
    

    给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。

    一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。

        5
       / 
      4   6
     /     
    2       7
    

    另一个正确答案是 [5,2,6,null,4,null,7]。

        5
       / 
      2   6
          
        4   7
    
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) {
                return null;
            }
            if (key < root.val) {
                // 待删除节点在左子树中
                root.left = deleteNode(root.left, key);
                return root;
            } else if (key > root.val) {
                // 待删除节点在右子树中
                root.right = deleteNode(root.right, key);
                return root;
            } else {
                // key == root.val,root 为待删除节点
                if (root.left == null) {
                    // 返回右子树作为新的根
                    return root.right;
                } else if (root.right == null) {
                    // 返回左子树作为新的根
                    return root.left;
                } else {
                    // 左右子树都存在,返回后继节点(右子树最左叶子)作为新的根
                    TreeNode successor = min(root.right);
                    successor.right = deleteMin(root.right);
                    successor.left = root.left;
                    return successor;
                }
            }
        }
    
        private TreeNode min(TreeNode node) {
            if (node.left == null) {
                return node;
            }
            return min(node.left);
        }
    
        private TreeNode deleteMin(TreeNode node) {
            if (node.left == null) {
                return node.right;
            }
            node.left = deleteMin(node.left);
            return node;
        }
    }
    
  • 相关阅读:
    POJ 1887 Testing the CATCHER
    HDU 3374 String Problem
    HDU 2609 How many
    POJ 1509 Glass Beads
    POJ 1458 Common Subsequence
    POJ 1159 Palindrome
    POJ 1056 IMMEDIATE DECODABILITY
    POJ 3080 Blue Jeans
    POJ 1200 Crazy Search
    软件体系结构的艺术阅读笔记1
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946467.html
Copyright © 2011-2022 走看看