LeetCode 题解工作台
二叉搜索树中的插入操作
给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value ,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。 注意 ,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。 …
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
如果根节点为空,我们直接创建一个新节点,值为 ,并返回。 如果根节点的值大于 ,我们递归地将 插入到左子树中,并将左子树的根节点更新为返回后的根节点。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value ,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。
示例 1:
输入:root = [4,2,7,1,3], val = 5 输出:[4,2,7,1,3,5] 解释:另一个满足题目要求可以通过的树是:![]()
示例 2:
输入:root = [40,20,60,10,30,50,70], val = 25 输出:[40,20,60,10,30,50,70,null,null,25]
示例 3:
输入:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 输出:[4,2,7,1,3,5]
提示:
- 树中的节点数将在
[0, 104]的范围内。 -108 <= Node.val <= 108- 所有值
Node.val是 独一无二 的。 -108 <= val <= 108- 保证
val在原始BST中不存在。
解题思路
方法一:递归
如果根节点为空,我们直接创建一个新节点,值为 ,并返回。
如果根节点的值大于 ,我们递归地将 插入到左子树中,并将左子树的根节点更新为返回后的根节点。
如果根节点的值小于 ,我们递归地将 插入到右子树中,并将右子树的根节点更新为返回后的根节点。
时间复杂度 ,空间复杂度 。其中 是二叉树的节点数。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root is None:
return TreeNode(val)
if root.val > val:
root.left = self.insertIntoBST(root.left, val)
else:
root.right = self.insertIntoBST(root.right, val)
return root
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate explain the difference between recursive and iterative approaches for tree traversal?
- question_mark
Does the candidate consider tree balancing or assume the tree is balanced in all cases?
- question_mark
Is the candidate able to identify and justify the time and space complexity for the given approaches?
常见陷阱
外企场景- error
Forgetting to return the root of the tree after the insertion is complete.
- error
Assuming that the tree is balanced without confirming or addressing balancing in the problem.
- error
Inserting the value incorrectly by not respecting the binary search tree properties (left < root < right).
进阶变体
外企场景- arrow_right_alt
What if the tree is a complete binary tree?
- arrow_right_alt
How does the solution change if the tree is unbalanced?
- arrow_right_alt
Can you handle cases where the tree is initially empty?