-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthAncestorNode.java
More file actions
48 lines (38 loc) · 1.06 KB
/
KthAncestorNode.java
File metadata and controls
48 lines (38 loc) · 1.06 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
package Trees;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class KthAncestorNode {
static int kthAncestor(Node root, Node node, int k) {
Stack<Node> s = new Stack<>();
List<Integer> ancestors = new ArrayList<>();
boolean found = false;
while (root != null || !s.empty()) {
if (root != null) {
s.push(root);
root = root.left;
} else {
Node temp = s.pop();
if (temp.val == node.val) {
found = true;
break;
}
if (temp.right != null) {
root = temp.right;
}
}
}
if (!found) return -1;
while (!s.empty() && k > 0) {
Node temp = s.pop();
ancestors.add(temp.val);
k--;
}
if (k > 0) {
return -1;
}
return ancestors.get(ancestors.size() - 1);
}
public static void main(String[] args) {
}
}