forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree_traversal.java
75 lines (68 loc) · 2.57 KB
/
Tree_traversal.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
73
74
75
class Node {
public int value;
public Node left, right;
public Node(int element)
{
value = element;
left = right = null;
}
}
class Tree {
Node root; /* root of the tree */
Tree() { root = null; }
/*function to print the nodes of given binary in Preorder*/
void traversePreorder(Node node)
{
if (node == null)
return;
System.out.print(node.value + " ");
traversePreorder(node.left);
traversePreorder(node.right);
}
/*function to print the nodes of given binary in Inorder*/
void traverseInorder(Node node)
{
if (node == null)
return;
traverseInorder(node.left);
System.out.print(node.value + " ");
traverseInorder(node.right);
}
/*function to print the nodes of given binary in Postorder*/
void traversePostorder(Node node)
{
if (node == null)
return;
traversePostorder(node.left);
traversePostorder(node.right);
System.out.print(node.value + " ");
}
void traversePreorder() { traversePreorder(root); }
void traverseInorder() { traverseInorder(root); }
void traversePostorder() { traversePostorder(root); }
public static void main(String args[])
{
Tree pt = new Tree();
pt.root = new Node(36);
pt.root.left = new Node(26);
pt.root.right = new Node(46);
pt.root.left.left = new Node(21);
pt.root.left.right = new Node(31);
pt.root.left.left.left = new Node(11);
pt.root.left.left.right = new Node(24);
pt.root.right.left = new Node(41);
pt.root.right.right = new Node(56);
pt.root.right.right.left = new Node(51);
pt.root.right.right.right = new Node(66);
System.out.println();
System.out.println("The Preorder traversal of given binary tree is - ");
pt.traversePreorder();
System.out.println("\n");
System.out.println("The Inorder traversal of given binary tree is - ");
pt.traverseInorder();
System.out.println("\n");
System.out.println("The Postorder traversal of given binary tree is - ");
pt.traversePostorder();
System.out.println();
}
}