-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSolution.java
42 lines (38 loc) · 1.06 KB
/
Solution.java
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
/**
* 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> pPath = getPath(root,p);
List<TreeNode> qPath = getPath(root,q);
TreeNode common = null;
for(int i=0; i<pPath.size()&&i<qPath.size();i++){
if(pPath.get(i) == qPath.get(i)){
common = pPath.get(i);
}else{
break;
}
}
return common;
}
public List<TreeNode> getPath(TreeNode root, TreeNode target){
List<TreeNode> treeNodePath = new ArrayList();
TreeNode node = root;
while(node!=target){
treeNodePath.add(node);
if(node.val > target.val){
node = node.left;
}else{
node = node.right;
}
}
treeNodePath.add(target);
return treeNodePath;
}
}