File tree Expand file tree Collapse file tree 1 file changed +92
-0
lines changed Expand file tree Collapse file tree 1 file changed +92
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ *
3
+ * @author Varun Upadhyay (https://github.com/varunu28)
4
+ *
5
+ */
6
+
7
+ // Driver Program
8
+ public class TreeTraversal {
9
+ public static void main (String [] args ) {
10
+ Node tree = new Node (5 );
11
+ tree .insert (3 );
12
+ tree .insert (7 );
13
+
14
+ // Prints 3 5 7
15
+ tree .printInOrder ();
16
+ System .out .println ();
17
+
18
+ // Prints 5 3 7
19
+ tree .printPreOrder ();
20
+ System .out .println ();
21
+
22
+ // Prints 3 7 5
23
+ tree .printPostOrder ();
24
+ System .out .println ();
25
+ }
26
+ }
27
+
28
+ /**
29
+ * The Node class which initializes a Node of a tree
30
+ * Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder
31
+ * printInOrder: LEFT -> ROOT -> RIGHT
32
+ * printPreOrder: ROOT -> LEFT -> RIGHT
33
+ * printPostOrder: LEFT -> RIGHT -> ROOT
34
+ */
35
+ class Node {
36
+ Node left , right ;
37
+ int data ;
38
+
39
+ public Node (int data ) {
40
+ this .data = data ;
41
+ }
42
+
43
+ public void insert (int value ) {
44
+ if (value < data ) {
45
+ if (left == null ) {
46
+ left = new Node (value );
47
+ }
48
+ else {
49
+ left .insert (value );
50
+ }
51
+ }
52
+ else {
53
+ if (right == null ) {
54
+ right = new Node (value );
55
+ }
56
+ else {
57
+ right .insert (value );
58
+ }
59
+ }
60
+ }
61
+
62
+ public void printInOrder () {
63
+ if (left != null ) {
64
+ left .printInOrder ();
65
+ }
66
+ System .out .print (data + " " );
67
+ if (right != null ) {
68
+ right .printInOrder ();
69
+ }
70
+ }
71
+
72
+ public void printPreOrder () {
73
+ System .out .print (data + " " );
74
+ if (left != null ) {
75
+ left .printPreOrder ();
76
+ }
77
+ if (right != null ) {
78
+ right .printPreOrder ();
79
+ }
80
+ }
81
+
82
+ public void printPostOrder () {
83
+ if (left != null ) {
84
+ left .printPostOrder ();
85
+ }
86
+ if (right != null ) {
87
+ right .printPostOrder ();
88
+ }
89
+ System .out .print (data + " " );
90
+ }
91
+ }
92
+
You can’t perform that action at this time.
0 commit comments