-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathTreeTraversal.java
54 lines (51 loc) · 1.29 KB
/
TreeTraversal.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
package SummerTrainingGFG.Tree;
/**
* @author Vishal Singh
*/
public class TreeTraversal {
static class Node{
int key;
Node left;
Node right;
Node(int key){
this.key = key;
}
}
static void inOrder(Node root){
//Left Root Right
if (root!=null){
inOrder(root.left);
System.out.print(root.key+" ");
inOrder(root.right);
}
}
static void postOrder(Node root){
//Left Right Root
if (root!=null){
postOrder(root.left);
postOrder(root.right);
System.out.print(root.key+" ");
}
}
static void preOrder(Node root){
//Root Left Right
if (root!=null){
System.out.print(root.key+" ");
preOrder(root.left);
preOrder(root.right);
}
}
public static void main(String[] args) {
Node root = new Node(10);
root.left = new Node(20);
root.left.left = new Node(40);
root.left.right = new Node(50);
root.right = new Node(30);
System.out.println("In Order");
inOrder(root);
System.out.println("\nPost Order");
postOrder(root);
System.out.println("\nPre Order");
preOrder(root);
}
}