`
import java.util.*;/** public class TreeNode {* int val = 0;* TreeNode left = null;* TreeNode right = null;* }*/public class Solution {/*** * @param root TreeNode类 * @param o1 int整型 * @param o2 int整型 * @return int整型*/public boolean flag=false;public void dfs(TreeNode root,ArrayList<Integer> path,int o){if(flag || root==null){return;}path.add(root.val);if(root.val==o){flag=true;return;}dfs(root.left,path,o);dfs(root.right,path,o);if(flag){return;}path.remove(path.size()-1);}public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
ArrayList<Integer> path1=new ArrayList<Integer>();
ArrayList<Integer> path2=new ArrayList<Integer>();
dfs(root,path1,o1);
flag=false;
dfs(root,path2,o2);
int res=0;
for(int i=0;i<path1.size()&&i<path2.size();i++){int x=path1.get(i);int y=path2.get(i);if(x==y){res=x;}elsebreak;
}
return res;// write code here}
}
import java.util.*;/** public class TreeNode {* int val = 0;* TreeNode left = null;* TreeNode right = null;* public TreeNode(int val) {* this.val = val;* }* }*/public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param root TreeNode类 * @param p int整型 * @param q int整型 * @return int整型*/public ArrayList<Integer>getPath(TreeNode root,int target){ArrayList<Integer> path1=new ArrayList<Integer>();TreeNode node=root;while(root.val!=target){path1.add(root.val);if(target<root.val){root=root.left;}else{root=root.right;}path1.add(root.val);} return path1;}public int lowestCommonAncestor (TreeNode root, int p, int q) {// write code hereArrayList<Integer> Path_p=new ArrayList<Integer>();ArrayList<Integer> path_q=new ArrayList<Integer>();int res=0;for(int i=0;i<Path_p.size()&&i<path_q.size();i++){int x=Path_p.get(i);int y=path_q.get(i);if(x==y){res=x;}else break;}return res;}
}