-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathToGivenNode.java
More file actions
33 lines (31 loc) · 863 Bytes
/
PathToGivenNode.java
File metadata and controls
33 lines (31 loc) · 863 Bytes
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
// https://www.interviewbit.com/problems/path-to-given-node/
// #tree #binary-tree
/**
* Definition for binary tree class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int
* x) { val = x; left=null; right=null; } }
*/
public class Solution {
public int[] solve(TreeNode A, int B) {
Deque<TreeNode> deque = new LinkedList<>();
DFS(deque, A, B);
int[] result = new int[deque.size()];
for (int i = 0; i < result.length; i++) {
result[i] = deque.pollFirst().val;
}
return result;
}
private boolean DFS(Deque<TreeNode> stack, TreeNode node, int B) {
if (node == null) {
return false;
}
stack.offerLast(node);
if (node.val == B) {
return true;
}
if (DFS(stack, node.left, B) || DFS(stack, node.right, B)) {
return true;
}
stack.pollLast();
return false;
}
}