-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.java
More file actions
92 lines (74 loc) · 2.17 KB
/
BinarySearchTree.java
File metadata and controls
92 lines (74 loc) · 2.17 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
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.Scanner;
public class BinarySearchTree {
static Node root = null;
public static class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
this.left=null;
this.right=null;
}
}
Node insert(Node node,int data){
if(root==null){
root =new Node(data);
return null;
}
else if(data > node.data){
if(node.right==null){
node.right=new Node(data);
}
insert(node.right, data);
}
else if(data < node.data){
if(node.left==null){
node.left=new Node(data);
}
insert(node.left, data);
}
return null;
}
//pre-order traversal
void printPreOrder(Node temp){
if(temp==null)
return;
System.out.print(temp.data +" ");
printPreOrder(temp.left);
printPreOrder(temp.right);
}
//post-order traversal
void printPostOrder(Node temp){
if(temp==null)
return;
printPostOrder(temp.left);
printPostOrder(temp.right);
System.out.print(temp.data +" ");
}
//in-order traversal
void printInOrder(Node temp){
if(temp==null)
return;
printInOrder(temp.left);
System.out.print(temp.data +" ");
printInOrder(temp.right);
}
public static void main(String[] args){
BinarySearchTree obj = new BinarySearchTree();
int i = 0;
int a[]={11,13,10,49,79,15};
while(i<a.length){
obj.insert(root,a[i]);
i++;
}
System.out.print("Pre-Order: ");
obj.printPreOrder(root);
System.out.println();
System.out.print("In-Order: ");
obj.printInOrder(root);
System.out.println();
System.out.print("Post-Order: ");
obj.printPostOrder(root);
}
}