• LeetCode 701. Insert into a Binary Search Tree


    LeetCode 701. Insert into a Binary Search Tree (二叉搜索树中的插入操作)

    题目

    链接

    https://leetcode.cn/problems/insert-into-a-binary-search-tree/

    问题描述

    给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value ,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。

    注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。

    示例

    输入:root = [4,2,7,1,3], val = 5
    输出:[4,2,7,1,3,5]

    提示

    树中的节点数将在 [0, 104]的范围内。
    -108 <= Node.val <= 108
    所有值 Node.val 是 独一无二 的。
    -108 <= val <= 108
    保证 val 在原始BST中不存在。

    思路

    直接借助二叉搜索树的性质,进行插入即可,需要注意的是返回值。

    复杂度分析

    时间复杂度 O(log2n)
    空间复杂度 O(1)
    

    代码

    Java

        public TreeNode insertIntoBST(TreeNode root, int val) {
            if (root == null) {
                root = new TreeNode(val);
                return root;
            }
            if (val > root.val) {
                if (root.right == null) {
                    root.right = new TreeNode(val);
                } else {
                    insertIntoBST(root.right, val);
                }
            } else {
                if (root.left == null) {
                    root.left = new TreeNode(val);
                } else {
                    insertIntoBST(root.left, val);
                }
            }
            return root;
        }
    
  • 相关阅读:
    ZOJ2334 Monkey King 并查集 STL
    ZOJ2286 Sum of Divisors 筛选式打表
    ZOJ2105 终于找到错误
    ZOJ-2091-Mean of Subsequence (反证法的运用!!)
    【9929】潜水员
    【9928】混合背包
    【t077】宝物筛选
    【9927】庆功会
    【9926】完全背包
    【9925】0/1背包
  • 原文地址:https://www.cnblogs.com/blogxjc/p/16361870.html
Copyright © 2020-2023  润新知