zoukankan      html  css  js  c++  java
  • 【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)。
  • 相关阅读:
    在Python中使用多进程快速处理数据
    深度学习中Embedding层有什么用?
    split("\s+") 和 split(" +") 有什么区别?
    python merge、concat合并数据集
    机器学习中常见的损失函数
    XGBoost、LightGBM的详细对比介绍
    $(function(){})的执行过程分析
    jQuery.extend({...})分析
    jquery核心功能分析
    print打印网页相关
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13308046.html
Copyright © 2011-2022 走看看