-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
49 lines (41 loc) · 1.19 KB
/
Solution.java
File metadata and controls
49 lines (41 loc) · 1.19 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
import java.util.ArrayList;
import java.util.List;
import javax.swing.tree.TreeNode;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> path1 = getPath(root,p);
List<TreeNode> path2 = getPath(root,q);
TreeNode ancestor = null;
for(int i =0 ; i<path1.size()&&i<path2.size();i++){
if(path1.get(i)==path2.get(i)){
ancestor = path1.get(i);
}else{
break;
}
}
return ancestor;
}
private List<TreeNode> getPath(TreeNode root, TreeNode targTreeNode) {
List<TreeNode> path = new ArrayList<>();
TreeNode curNode = root;
while(curNode!=targTreeNode){
path.add(curNode);
if(curNode.val>targTreeNode.val){
curNode = curNode.left;
}else{
curNode = curNode.right;
}
}
path.add(curNode);
return path;
}
}