Repository navigation
Expand file tree
/
Copy pathBinaryTreePathFromRootToNode.java
More file actions
66 lines (49 loc) · 1.78 KB
/
Copy pathBinaryTreePathFromRootToNode.java
File metadata and controls
66 lines (49 loc) · 1.78 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
package com.abn.dsalgos.datastructure.binaryTree;
import com.abn.dsalgos.utils.MyTreeNode;
import java.util.Stack;
/*
Find the path of a node from root for binary tree.
*/
public class BinaryTreePathFromRootToNode<T> {
MyTreeNode root;
public BinaryTreePathFromRootToNode() {
root = null;
}
public Stack<MyTreeNode> getPathAsStack(MyTreeNode node, T value) {
Stack<MyTreeNode> stack = new Stack<>();
stack.push(node);
if (node.data == value) {
return stack;
}
MyTreeNode currentNode = node;
while (!stack.isEmpty()) {
while (currentNode.left != null && !currentNode.left.isVisited) {
currentNode.left.isVisited = true;
stack.push(currentNode.left);
if (currentNode.left.data == value) {
return stack;
} else {
currentNode = currentNode.left;
}
}
while (currentNode.right != null && !currentNode.right.isVisited) {
currentNode.right.isVisited = true;
stack.push(currentNode.right);
if (currentNode.right.data == value) {
return stack;
} else {
currentNode = currentNode.right;
}
}
if ((currentNode.left == null && currentNode.right == null) || (currentNode.left.isVisited && currentNode.right.isVisited)) {
stack.pop();
}
currentNode = stack.peek();
}
throw new RuntimeException("unexpected");
}
public void getPath(MyTreeNode node, T value) {
Stack<MyTreeNode> pathAsStack = getPathAsStack(node, value);
System.out.println(pathAsStack);
}
}