-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Solution.java
42 lines (38 loc) · 944 Bytes
/
Solution.java
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
// github.com/RodneyShag
/* Node is defined as :
class Node {
int data;
Node left;
Node right;
}
*/
// Runtime: O(log n) on a balanced tree.
// Space Complexity: O(1)
static Node Insert(Node root, int value) {
/* Create new Node */
Node newNode = new Node();
newNode.data = value;
/* Special case: empty tree */
if (root == null) {
return newNode;
}
/* Iteratively walk tree and insert new Node */
Node curr = root;
while (true) {
if (value <= curr.data) {
if (curr.left == null) {
curr.left = newNode;
return root;
} else {
curr = curr.left;
}
} else {
if (curr.right == null) {
curr.right = newNode;
return root;
} else {
curr = curr.right;
}
}
}
}