-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
80 lines (74 loc) · 1.97 KB
/
BinarySearchTree.java
File metadata and controls
80 lines (74 loc) · 1.97 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.*;
/* This program is to implement binary search tree. Node class decalres the right child, left child and the data.
Tree class is to perform the functions like inserting element and printing it in all the traversal method. */
class Node {
int data;
Node left;
Node right;
public Node(int data){
this.left = null;
this.right = null;
this.data = data;
}
}
class Tree {
Node root;
Tree(Node root) {
this.root = root;
}
void insertTree(Node node, int data) {
if(node.data > data) {
if(node.left != null) {
insertTree(node.left, data);
} else {
Node newNode = new Node(data);
node.left = newNode;
}
} else {
if(node.right != null){
insertTree(node.right, data);
} else {
Node newNode = new Node(data);
node.right = newNode;
}
}
return ;
}
void inOrderPrintTree(Node root) {
if(root == null)
return;
inOrderPrintTree(root.right);
System.out.println(root.data);
inOrderPrintTree(root.left);
return;
}
void preOrderPrintTree(Node root) {
if(root == null)
return;
System.out.println(root.data);
preOrderPrintTree(root.left);
preOrderPrintTree(root.right);
}
void postOrderPrintTree(Node root) {
if(root == null)
return;
preOrderPrintTree(root.left);
preOrderPrintTree(root.right);
System.out.println(root.data);
}
}
class BinarySearchTree{
public static void main(String[] args) {
Tree T = new Tree(new Node(1));
T.insertTree(T.root, 2);
T.insertTree(T.root, 3);
T.insertTree(T.root, 4);
T.insertTree(T.root, 5);
System.out.println("In-Order Traversal");
T.inOrderPrintTree(T.root);
System.out.println("Pre-Order Traversal");
T.preOrderPrintTree(T.root);
System.out.println("Post-Order Traversal");
T.postOrderPrintTree(T.root);
}
}