-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarytree.java
More file actions
78 lines (67 loc) · 1.68 KB
/
Copy pathBinarytree.java
File metadata and controls
78 lines (67 loc) · 1.68 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
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
public class Binarytree {
Node root;
Binarytree() {
root = null;
}
void insert(int data) {
root = insertRec(root, data);
}
Node insertRec(Node root, int data) {
if (root == null) {
root = new Node(data);
return root;
}
if (data < root.data) {
root.left = insertRec(root.left, data);
} else if (data > root.data) {
root.right = insertRec(root.right, data);
}
return root;
}
void preorder(Node root) {
if (root != null) {
System.out.print(root.data + " ");
preorder(root.left);
preorder(root.right);
}
}
void inorder(Node root) {
if (root != null) {
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
}
void postorder(Node root) {
if (root != null) {
postorder(root.left);
postorder(root.right);
System.out.print(root.data + " ");
}
}
public static void main(String args[]) {
Binarytree b = new Binarytree();
b.insert(50);
b.insert(30);
b.insert(20);
b.insert(40);
b.insert(70);
b.insert(60);
b.insert(80);
System.out.println("Preorder");
b.preorder(b.root);
System.out.println("\nInorder ");
b.inorder(b.root);
System.out.println("\nPostorder ");
b.postorder(b.root);
}
}