题目:Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
解题思路:两个节点的最低公共祖先,先找到根节点到两个节点的路径,两个路径的相同点就是公共祖先,找最靠后的相同点
代码:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
boolean find = false;
public void findPath(TreeNode root, TreeNode target, ArrayList<TreeNode> list){
if(root == null) return;
list.add(root);
if(root == target) {
find = true;
return;
}
if(!find && root.left!=null)
findPath(root.left,target,list);
if(!find && root.right!=null)
findPath(root.right,target,list);
if(!find)
list.remove(list.size()-1);
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
ArrayList<TreeNode> list1 = new ArrayList<>();
ArrayList<TreeNode> list2 = new ArrayList<>();
findPath(root,p,list1);
find = false;
findPath(root,q,list2);
int len = Math.min(list1.size(),list2.size());
for (int i = 0;i<len;i++){
if(list1.get(i) == list2.get(i))
return list1.get(i);
}
return null;
}