• 【LeetCode】701.二叉搜索树中的插入操作(递归+迭代,图解,java实现)


    题目

    image-20200620231502250

    题解

    概述

    二叉搜索树的巨大优势就是:在平均情况下,能够在O(log*N*)的时间内完成搜索和插入元素。

    二叉搜索树的插入方法非常简单,我们将插入的节点作为叶子节点的子节点插入。插入到哪个叶节点可以遵循以下原则:

    • val > node.val,插入到右子树。
    • val < node.val,插入到左子树。

    在这里插入图片描述

    方法一:递归

    算法:

    • root == null,则返回 TreeNode(val)
    • val > root.val,插入到右子树。
    • val < root.val,插入到左子树。
    • 返回 root

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    class Solution {
      public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);
    
        // insert into the right subtree
        if (val > root.val) root.right = insertIntoBST(root.right, val);
        // insert into the left subtree
        else root.left = insertIntoBST(root.left, val);
        return root;
      }
    }
    

    复杂度分析

    • 时间复杂度:O(H),其中H指的是树的高度。平均情况下 O(logN),最坏的情况下O(N)。
    • 空间复杂度:平均情况下O(H)。最坏的情况下是 O(N),是在递归过程中堆栈使用的空间。

    方法二:迭代

    上面的递归可以转换成迭代的解决方案。

    class Solution {
      public TreeNode insertIntoBST(TreeNode root, int val) {
        TreeNode node = root;
        while (node != null) {
          // insert into the right subtree
          if (val > node.val) {
            // insert right now
            if (node.right == null) {
              node.right = new TreeNode(val);
              return root;
            }
            else node = node.right;
          }
          // insert into the left subtree
          else {
            // insert right now
            if (node.left == null) {
              node.left = new TreeNode(val);
              return root;
            }
            else node = node.left;
          }
        }
        return new TreeNode(val);
      }
    }
    

    复杂度分析

    • 时间复杂度:O(H),其中 HH 指的是树的高度。平均情况下O(logN),最坏的情况下O(N)。
    • 空间复杂度:O(1)。
  • 相关阅读:
    [LeetCode 220.] 存在重复元素 III
    C++ 构造函数 & 析构函数
    [LeetCode 891.] 子序列宽度之和【hard】
    [LeetCode 447.] Number of Boomerangs
    HJ93 数组分组
    HJ77 火车进站
    [LeetCode 338.] 比特位计数
    线段树
    大数量问题的一般解决方法
    字典树
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13308046.html
Copyright © 2020-2023  润新知