forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertIntoBinarySearchTree.java
More file actions
64 lines (52 loc) · 1.5 KB
/
InsertIntoBinarySearchTree.java
File metadata and controls
64 lines (52 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package binary_search_tree;
/**
* Description: https://leetcode.com/problems/insert-into-a-binary-search-tree
* Difficulty: Medium
*/
public class InsertIntoBinarySearchTree {
/**
* Time complexity: O(h)
* Space complexity: O(1)
*/
public TreeNode insertIntoBSTViaIteration(TreeNode root, int val) {
TreeNode current = root;
while (current != null) {
if (current.val > val) {
if (current.left == null) {
current.left = new TreeNode(val);
return root;
}
current = current.left;
} else {
if (current.right == null) {
current.right = new TreeNode(val);
return root;
}
current = current.right;
}
}
return new TreeNode(val);
}
/**
* Time complexity: O(h)
* Space complexity: O(h)
*/
public TreeNode insertIntoBSTViaRecursion(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
if (root.val > val) {
root.left = insertIntoBSTViaRecursion(root.left, val);
}
if (root.val < val) {
root.right = insertIntoBSTViaRecursion(root.right, val);
}
return root;
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
}