⚡Flashcard Drill➔
NeetCode #422LC-701MediumTreesNC 250
← Back to All Problems

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

📌 Problem Statement & Constraints

You are given the root of a binary search tree and a value val to insert. Insert the value and return the root. The input tree is guaranteed to be a valid BST and val does not already exist in it. Constraints: the number of nodes is in [0, 10^4].

💡 Core Algorithmic Approaches

  1. A BST insert is a guided descent: go left when val is smaller, right when larger.
  2. The insertion point is the first empty slot, where a new node replaces None.
  3. The recursive form assigns the result back to the child pointer, which handles both the descent and the linking in one expression.
  4. An iterative version keeps a parent pointer and links the new node at the end.

💻 Benchmark Python3 Implementation

class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root:
            return TreeNode(val)           # empty slot -> insert here
        if val < root.val:
            root.left = self.insertIntoBST(root.left, val)
        else:
            root.right = self.insertIntoBST(root.right, val)
        return root


# Iterative variant
class Solution2:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        node = TreeNode(val)
        if not root:
            return node
        cur = root
        while True:
            if val < cur.val:
                if cur.left:
                    cur = cur.left
                else:
                    cur.left = node
                    return root
            else:
                if cur.right:
                    cur = cur.right
                else:
                    cur.right = node
                    return root

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(h): the descent follows one path, where h is the tree height.
💾 Space Complexity
O(h) for the recursion, O(1) for the iterative version.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting to return the new node when root is None: the insertion would be lost.
  • Not assigning the recursive result back: self.insertIntoBST(root.left, val) without assignment does nothing to the tree.
  • Assuming the tree stays balanced: a sorted insertion order produces a degenerate tree of height n.
  • Handling duplicates: the problem guarantees val is absent, so no duplicate policy is needed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

二叉搜索树中的插入操作

给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value,将值插入二叉搜索树。返回插入后二叉搜索树的根节点。输入数据 保证 新值和原始二叉搜索树中的任意节点值都不同。注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。你可以返回 任意 有效的结果。约束:树中的节点数将在 [0, 10^4] 的范围内;-10^8 ≤ Node.val ≤ 10^8;-10^8 ≤ val ≤ 10^8;保证 val 在原始 BST 中不存在。

核心要点

  • 递归插入(标准解) :若 val &lt; root.val 则递归插入左子树,否则插入右子树;遇到空节点则创建新节点。
  • 为什么只需走到空位 :BST 的插入位置是唯一的——沿比较路径下行,第一个空位置就是新节点的位置。
  • 迭代插入 :用 while 循环沿路径下行,找到空位置后挂上新节点,空间 O(1)。
  • 返回值 :递归版本返回当前子树的根;若树为空则返回新节点。

常见陷阱

  • 忘记 root.left = ... 的赋值 :递归返回值必须挂回父节点,否则新节点会丢失。
  • 插入后未保持 BST 性质 :必须沿比较路径下行,不能随意挂在某个空位。
  • 比较用 &lt;= :题目保证新值与已有值都不同,用 &lt; 或 &lt;= 结果相同。
  • 空树 :直接返回新节点。

参考实现

class Solution:
    def insertIntoBST(self, root: 'TreeNode', val: int) -> 'TreeNode':
        if not root:
            return TreeNode(val)                # 找到空位,创建节点
        if val < root.val:
            root.left = self.insertIntoBST(root.left, val)
        else:
            root.right = self.insertIntoBST(root.right, val)
        return root

# 迭代版本(空间 O(1))
# def insertIntoBST(self, root, val):
#     node = TreeNode(val)
#     if not root: return node
#     cur = root
#     while True:
#         if val < cur.val:
#             if cur.left: cur = cur.left
#             else: cur.left = node; break
#         else:
#             if cur.right: cur = cur.right
#             else: cur.right = node; break
#     return root