Skip to content

Commit 554bec0

Browse files
author
Octa
committed
Binary search tree
1 parent bec471b commit 554bec0

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

src/main/java/com/datastructures/tree/BinarySearchTree.java

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,45 @@ public Node insertIteratively(Node root, int value) {
4242

4343
}
4444

45-
/*public Tree insertRecursively(Tree root, int value) {
45+
public static Node insertRecursively(Node root, int value) {
4646

47-
}*/
47+
if(root == null) {
48+
root = new Node(value);
49+
return root;
50+
}
51+
52+
if(root.value <= value) {
53+
root.right = insertRecursively(root.right, value);
54+
}
55+
else {
56+
root.left = insertRecursively(root.left, value);
57+
}
58+
59+
return root;
60+
61+
}
62+
63+
public static void inorder(Node root)
64+
{
65+
if (root == null) {
66+
return;
67+
}
68+
69+
inorder(root.left);
70+
System.out.print(root.value + " ");
71+
inorder(root.right);
72+
}
4873

4974
public static void main(String[] args) {
5075

76+
int[] values = {15, 10, 20, 8, 12, 16, 25};
77+
78+
Node root = null;
79+
for(int val: values) {
80+
root = insertRecursively(root, val);
81+
}
82+
83+
inorder(root);
5184
}
5285

5386

0 commit comments

Comments
 (0)