DeepSeek LeetCode 701. Insert into a Binary Search Tree Java Implement

本文详解LeetCode 701题——在二叉搜索树(BST)中插入新节点的Java实现,涵盖递归与迭代两种方法。递归法时间/空间复杂度均为O(h),迭代法空间复杂度优化至O(1)。重点强调BST性质(左小右大)、空节点为插入位置、无需处理重复值及不需自平衡等关键约束。适用于后端开发与算法面试准备。

LeetCode 701. Insert into a Binary Search Tree

Given a BST root and a value, insert the value while keeping it a valid BST. The new value is guaranteed to not already exist in the tree.


Approach 1: Recursive (Cleanest)

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);

        if (val < root.val) {
            root.left = insertIntoBST(root.left, val);
        } else {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }
}

Complexity: O(h) time, O(h) stack space — where h is tree height (O(log n) balanced, O(n) worst case).


Approach 2: Iterative

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        TreeNode node = new TreeNode(val);
        if (root == null) return node;

        TreeNode cur = root;
        while (true) {
            if (val < cur.val) {
                if (cur.left == null) {
                    cur.left = node;
                    break;
                }
                cur = cur.left;
            } else {
                if (cur.right == null) {
                    cur.right = node;
                    break;
                }
                cur = cur.right;
            }
        }
        return root;
    }
}

Complexity: O(h) time, O(1) extra space.


Key Points

Point Explanation
BST property val < node.val → go left; val > node.val → go right
Base case root == null → this is where the new node belongs
No rebalancing The problem allows any valid BST, so we never restructure
Guaranteed unique Statement says val does not exist, so no duplicate handling needed
Return root Root itself never changes; original root is returned

Follow-up: What if the tree can become skewed?

If inputs are sorted, this naive insertion produces a linked list (O(n) depth). For self-balancing behavior, use an AVL tree or Red-Black tree with rotation after insertion — but that’s beyond LeetCode 701’s requirements.
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址