-
Notifications
You must be signed in to change notification settings - Fork 369
/
Copy pathtree_traversals.java
72 lines (59 loc) · 1.32 KB
/
tree_traversals.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
71
72
class tree_traversals {
class Node {
int item;
Node left, right;
public Node(int key) {
item = key;
left = right = null;
}
}
// Root of Binary Tree
Node root;
tree_traversals() {
root = null;
}
void postorder(Node node) {
if (node == null)
return;
// Traverse left
postorder(node.left);
// Traverse right
postorder(node.right);
// Traverse root
System.out.print(node.item + "->");
}
void inorder(Node node) {
if (node == null)
return;
// Traverse left
inorder(node.left);
// Traverse root
System.out.print(node.item + "->");
// Traverse right
inorder(node.right);
}
void preorder(Node node) {
if (node == null)
return;
// Traverse root
System.out.print(node.item + "->");
// Traverse left
preorder(node.left);
// Traverse right
preorder(node.right);
}
public static void main(String[] args) {
tree_traversals tree = new tree_traversals();
tree.root = new Node(1);
tree.root.left = new Node(12);
tree.root.right = new Node(9);
tree.root.left.left = new Node(5);
tree.root.left.right = new Node(6);
System.out.println("\n\nInorder traversal");
tree.inorder(tree.root);
System.out.println("\n\nPreorder traversal ");
tree.preorder(tree.root);
System.out.println("\n\nPostorder traversal");
tree.postorder(tree.root);
}
}