-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTraversals.java
More file actions
67 lines (59 loc) · 1.64 KB
/
Traversals.java
File metadata and controls
67 lines (59 loc) · 1.64 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
package Trees;
/*
* Travelling each and every element at least once.
* The space complexity for traversals of any binary tree is O(h), h is height.
* All these are Depth First Search Traversals (DFS).
*/
public class Traversals {
/*
* To do preorder traversal that is work -> left -> right.
*/
public static void preorder(Node root) {
if (root == null)
return;
System.out.print(root.val + " ");
preorder(root.left);
preorder(root.right);
}
/*
* To do inorder traversal that is left -> work -> right.
*/
public static void inorder(Node root) {
if (root == null)
return;
inorder(root.left);
System.out.print(root.val + " ");
inorder(root.right);
}
/*
* To do postorder traversal that is left -> right -> work.
*/
public static void postorder(Node root) {
if (root == null)
return;
postorder(root.left);
postorder(root.right);
System.out.print(root.val + " ");
}
public static void main(String[] args) {
// Creating a Binary Tree to display values and do traversals.
Node root = new Node(10);
Node a = new Node(20);
Node b = new Node(30);
root.left = a;
root.right = b;
Node c = new Node(40);
Node d = new Node(50);
a.left = c;
a.right = d;
Node e = new Node(60);
Node f = new Node(70);
b.right = e;
e.right = f;
preorder(root);
System.out.println();
inorder(root);
System.out.println();
postorder(root);
}
}