-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProblem_1.java
More file actions
66 lines (56 loc) · 1.46 KB
/
Copy pathProblem_1.java
File metadata and controls
66 lines (56 loc) · 1.46 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
65
66
package trees.binarySearchTree;
public class Problem_1 {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Node root;
// ! Constructor
Problem_1() {
root = null;
}
// This method mainly calls insertRec()
void insert(int key) {
root = insertRec(root, key);
}
// * A recursive function to insert a new key in BST
Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
// The method mainly calls InorderRec()
void inorder() {
inorderRec(root);
}
// ? A utility function to do inorder traversal of BST
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
public static void main(String[] args) {
Problem_1 tree = new Problem_1();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
// ? print inorder traversal of BST
tree.inorder();
}
}