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.

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

被折叠的 条评论
为什么被折叠?



