-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInOrderTraversal.java
43 lines (37 loc) · 1.21 KB
/
InOrderTraversal.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
package com.anudev.ds.trees;
import java.util.Stack;
public class InOrderTraversal {
public static void inOrderTraversal(Node node) {
System.out.print("Recursive In order traversal: \t\t");
recursiveInOrderTraversal(node);
System.out.println();
System.out.print("Non Recursive In order traversal: \t");
nonRecursiveInOrderTraversal(node);
System.out.println();
}
private static void recursiveInOrderTraversal(Node node) {
if (node != null) {
recursiveInOrderTraversal(node.getLeftNode());
System.out.print(node.getValue() + ",");
recursiveInOrderTraversal(node.getRightNode());
}
}
private static void nonRecursiveInOrderTraversal(Node node) {
if (node == null) {
return;
}
Stack<Node> stack = new Stack<>();
while (true) {
while (node != null) {
stack.push(node);
node = node.getLeftNode();
}
if (stack.isEmpty()) {
break;
}
node = stack.pop();
System.out.print(node.getValue() + ",");
node = node.getRightNode();
}
}
}