题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
/*
* 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 int lowestCommonAncestor (TreeNode root, int o1, int o2) {
// write code here
// 定义两个ArrayList 来保存o1,o2的祖先
ArrayList<Integer> o1Ancetors = new ArrayList<>();
ArrayList<Integer> o2Ancetors = new ArrayList<>();
int returnAncetor = -1;
// 求各自的祖先
getAncetor(root,o1,o1Ancetors);
getAncetor(root,o2,o2Ancetors);
for(int i = 0; i< o1Ancetors.size(); i++){
if(o2Ancetors.contains(o1Ancetors.get(i))){
returnAncetor = o1Ancetors.get(i);
break;
}
}
return returnAncetor;
}
public boolean getAncetor(TreeNode node,int target,ArrayList<Integer> list){
if(node == null){
return false;
}
if(node.val == target){
list.add(node.val);
return true;
}
if(getAncetor(node.left,target,list) || getAncetor(node.right,target,list)){
list.add(node.val);
return true;
}
return false;
}
}