-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathBinary tree in java
70 lines (58 loc) · 1.5 KB
/
Binary tree in java
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
public class BinaryTree {
static class node {
int data;
node left;
node right;
node(int data) {
this.data = data;
this.right = null;
this.left = null;
}
}
node root;
// Tree Traversals
// InOrder
void printInorder(node n) {
if (n == null)
return;
printInorder(n.left);
System.out.print(n.data + " ");
printInorder(n.right);
}
// PostOrder
void printPostOrder(node n) {
if (n == null)
return;
printPostOrder(n.left);
printPostOrder(n.right);
System.out.print(n.data + " ");
}
// PreOrder
void prinPreOrder(node n) {
if (n == null)
return;
System.out.print(n.data + " ");
prinPreOrder(n.left);
prinPreOrder(n.right);
}
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.root = new node(10);
bt.root.left = new node(20);
bt.root.right = new node(30);
bt.root.left.left = new node(40);
bt.root.left.right = new node(50);
bt.root.right.left = new node(60);
bt.root.right.right = new node(100);
// Traversals
// Inorder
bt.printInorder(bt.root);
System.out.println();
// postorder
bt.printPostOrder(bt.root);
System.out.println();
// postorder
bt.prinPreOrder(bt.root);
System.out.println();
}
}