题目
题解
概述
二叉搜索树的巨大优势就是:在平均情况下,能够在O(log*N*)
的时间内完成搜索和插入元素。
二叉搜索树的插入方法非常简单,我们将插入的节点作为叶子节点的子节点插入。插入到哪个叶节点可以遵循以下原则:
- 若
val > node.val
,插入到右子树。 - 若
val < node.val
,插入到左子树。
方法一:递归
算法:
- 若
root == null
,则返回TreeNode(val)
。 - 若
val > root.val
,插入到右子树。 - 若
val < root.val
,插入到左子树。 - 返回
root
。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
// insert into the right subtree
if (val > root.val) root.right = insertIntoBST(root.right, val);
// insert into the left subtree
else root.left = insertIntoBST(root.left, val);
return root;
}
}
复杂度分析
- 时间复杂度:O(H),其中H指的是树的高度。平均情况下 O(logN),最坏的情况下O(N)。
- 空间复杂度:平均情况下O(H)。最坏的情况下是 O(N),是在递归过程中堆栈使用的空间。
方法二:迭代
上面的递归可以转换成迭代的解决方案。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode node = root;
while (node != null) {
// insert into the right subtree
if (val > node.val) {
// insert right now
if (node.right == null) {
node.right = new TreeNode(val);
return root;
}
else node = node.right;
}
// insert into the left subtree
else {
// insert right now
if (node.left == null) {
node.left = new TreeNode(val);
return root;
}
else node = node.left;
}
}
return new TreeNode(val);
}
}
复杂度分析
- 时间复杂度:O(H),其中 HH 指的是树的高度。平均情况下O(logN),最坏的情况下O(N)。
- 空间复杂度:O(1)。