-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPreOrderTraversal.java
66 lines (56 loc) · 2.02 KB
/
PreOrderTraversal.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
package com.anudev.ds.trees;
import java.util.Stack;
public class PreOrderTraversal {
public static void preOrderTraversal(Node node) {
System.out.print("Recursive Pre order traversal: \t\t");
recursivePreOrderTraversal(node);
System.out.println();
System.out.print("Non Recursive Pre order traversal: \t");
nonRecursivePreOrderTraversal(node);
System.out.println();
System.out.print("Non Recursive Pre order traversal2: ");
nonRecursivePreOrderTraversal2(node);
System.out.println();
}
private static void recursivePreOrderTraversal(Node node) {
if (node != null) {
System.out.print(node.getValue() + ",");
recursivePreOrderTraversal(node.getLeftNode());
recursivePreOrderTraversal(node.getRightNode());
}
}
private static void nonRecursivePreOrderTraversal(Node node) {
Stack<Node> stack = new Stack<>();
stack.push(node);
while (!stack.isEmpty()) {
Node stackNode = stack.pop();
System.out.print(stackNode.getValue() + ",");
// add the right node first which will be processed later
if (stackNode.getRightNode() != null) {
stack.push(stackNode.getRightNode());
}
// add the left node which will be popped later
if (stackNode.getLeftNode() != null) {
stack.push(stackNode.getLeftNode());
}
}
}
private static void nonRecursivePreOrderTraversal2(Node node) {
if (node == null) {
return;
}
Stack<Node> stack = new Stack<>();
while (true) {
// keep pushing the left nodes
while (node != null) {
System.out.print(node.getValue() + ",");
stack.push(node);
node = node.getLeftNode();
}
if (stack.isEmpty()) {
break;
}
node = stack.pop().getRightNode();
}
}
}