题目链接
代码
递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (root.val > val) {
root.left = insertIntoBST(root.left, val);
} else {
root.right = insertIntoBST(root.right, val);
}
return root;
}
}迭代
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
TreeNode parent = root;
TreeNode node = root;
while (node != null) {
parent = node;
node = node.val > val ? node.left : node.right;
}
if (parent.val > val) {
parent.left = new TreeNode(val);
} else {
parent.right = new TreeNode(val);
}
return root;
}
}
复杂度分析
- 时间复杂度: O(n)
- 空间复杂度: O(1)