Skip to content

Commit 7eb86b0

Browse files
committed
feat: Solve bst-insertion
- Hackerrank
1 parent 10a264a commit 7eb86b0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

bst-insertion.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Hackerrank
3+
* You are given a pointer to the root of a binary search tree and values to be
4+
* inserted into the tree. Insert the values into their appropriate position in
5+
* the binary search tree and return the root of the updated binary tree. You
6+
* just have to complete the function.
7+
* Constraints:
8+
* 1. # Of nodes in the tree <= 500
9+
* This solution got 20 points
10+
* Problem link: http://hr.gs/cacecb
11+
*/
12+
13+
/* Node is defined as :
14+
class Node
15+
int data;
16+
Node left;
17+
Node right;
18+
*/
19+
20+
public static Node insert(Node root,int data) {
21+
if (root != null) {
22+
if (data >= root.data) {
23+
if (root.right == null) {
24+
root.right = new Node(data);
25+
} else {
26+
insert(root.right, data);
27+
}
28+
} else {
29+
if (root.left == null) {
30+
root.left = new Node(data);
31+
} else {
32+
insert(root.left, data);
33+
}
34+
}
35+
} else {
36+
root = new Node(data);
37+
}
38+
return root;
39+
}

0 commit comments

Comments
 (0)