-
Notifications
You must be signed in to change notification settings - Fork 22
/
PrintAllRootToLeafPaths.java
79 lines (65 loc) · 2.32 KB
/
PrintAllRootToLeafPaths.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
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.company.amazon;
import java.util.Stack;
import static com.company.amazon.BinaryTree.*;
public class PrintAllRootToLeafPaths {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
BinaryTree tree = new BinaryTree();
BinaryTree.Node node = new BinaryTree.Node(10);
node.left = new BinaryTree.Node(8);
node.right = new BinaryTree.Node(2);
node.right.left = new BinaryTree.Node(18);
node.left.left = new BinaryTree.Node(3);
node.left.right = new BinaryTree.Node(5);
tree.root = node;
// inorder(tree.root);
System.out.println("--------------------------Print All Path With Stack--------------------------");
printAllPath(tree.root, stack);
System.out.println("----------------------Print All Path Without Stack--------------------------");
printAllPathWithoutStack(tree.root, new int[100], -1);
}
public static void inorder(Node root) {
if (root == null)
return;
inorder(root.left);
System.out.println(root.data);
inorder(root.right);
}
public static void printAllPathWithoutStack(Node root, int[] path, int elements) {
if (root == null) {
return;
}
if (isLeafNode(root)) {
path[++elements] = root.data;
printPath(path, elements);
elements--;
return;
}
path[++elements] = root.data;
printAllPathWithoutStack(root.left, path, elements);
printAllPathWithoutStack(root.right, path, elements);
}
private static void printPath(int[] path, int elements) {
for (int i = 0; i <= elements; i++) {
System.out.print(path[i] + ",");
}
System.out.println();
}
public static void printAllPath(BinaryTree.Node root, Stack<Integer> stack) {
if (root == null)
return;
// Push The Element
stack.push(root.data);
// Traverse it's left
printAllPath(root.left, stack);
if (BinaryTree.isLeafNode(root)) {
System.out.println(stack);
stack.pop();
return;
}
// Traverse it's right
printAllPath(root.right, stack);
// Once done remove it from the stack
stack.pop();
}
}