Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f84ea90

Browse files
Create kthCommonAncestor.java
1 parent 423f0e3 commit f84ea90

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

‎kthCommonAncestor.java‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// User function Template for Java
2+
class Solution {
3+
public int kthCommonAncestor(Node root, int k, int x, int y) {
4+
Node LCA = lca(root, x, y);
5+
ArrayList<Integer> arr = new ArrayList<>();
6+
7+
search(root, LCA, arr);
8+
9+
return (arr.size() - k < 0) ? -1 : arr.get(arr.size() - k);
10+
}
11+
12+
void search(Node root, Node x, ArrayList<Integer> arr){
13+
while(root != null){
14+
arr.add(root.data);
15+
if(root.data == x.data){
16+
return;
17+
}
18+
if(root.data < x.data){
19+
root = root.right;
20+
}
21+
else{
22+
root = root.left;
23+
}
24+
}
25+
}
26+
27+
Node lca(Node root, int n1,int n2)
28+
{
29+
// Your code here
30+
if(root == null){
31+
return null;
32+
}
33+
34+
if(root.data == n1 || root.data == n2){
35+
return root;
36+
}
37+
38+
Node left = lca(root.left,n1,n2);
39+
Node right = lca(root.right,n1,n2);
40+
41+
if(left == null && right == null){
42+
return null;
43+
}
44+
45+
if(left != null && right != null){
46+
return root;
47+
}
48+
49+
if(left == null && right != null){
50+
return right;
51+
}
52+
53+
else{
54+
return left;
55+
}
56+
}
57+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /