-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryST.java
More file actions
87 lines (66 loc) · 2 KB
/
BinaryST.java
File metadata and controls
87 lines (66 loc) · 2 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
import java.util.Scanner;
public class BinaryST {
static Scanner sc = new Scanner(System.in);
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;
}
}
//creation of binary tree
Node create(int data){
Node newNode = new Node(data);
if(root==null)
root = newNode;
System.out.println();
if(data==-1)
return null;
System.out.println("Left");
int a =sc.nextInt();
newNode.left= create(a);
System.out.println("Right");
a =sc.nextInt();
newNode.right = create(a);
return newNode;
}
//pre order traversal
void printPreOrder(Node temp){
if(temp==null)
return;
System.out.print(temp.data +" ");
printPreOrder(temp.left);
printPreOrder(temp.right);
}
//post oreder 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){
BinaryST tree = new BinaryST();
System.out.println("Value of root: 1");
System.out.println();
tree.create(1);
tree.printPreOrder(root);
System.out.println();
tree.printInOrder(root);
System.out.println();
tree.printPostOrder(root);
}
}