思路:
1.找出根节点到p节点的路径;
2.找出根节点到q节点的路径;
3.遍历两条路径,找到最后相等的公共节点。
代码:
public class LCA {
List<TreeNode> list = new ArrayList<>();
List<TreeNode> listp = new ArrayList<>();
List<TreeNode> listq = new ArrayList<>();
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null)
return null;
preOrder(root,p,listp);
preOrder(root,q,listq);
// System.out.println(listp);
// System.out.println(listq);
int size1 = listp.size();
int size2 = listq.size();
int size = Math.min(size1, size2);
int idx=-1;
for (int i = 0; i < size; i++) {
if(listp.get(i)==listq.get(i))
idx=i;
}
if(idx==-1)
return null;
return listp.get(idx);
}
private void preOrder(TreeNode root, TreeNode p, List<TreeNode> listp) {
if(root==null)
return;
list.add(root);
if(list.get(list.size()-1)==p)
listp.addAll(list);
preOrder(root.left,p,listp);
preOrder(root.right,p,listp);
list.remove(list.size()-1);
}
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
TreeNode t6 = new TreeNode(6);
t1.left=t2;
t1.right=t3;
t2.left=t4;
t2.right=t5;
t4.left=null;
t4.right=null;
t5.left=t6;
t5.right=null;
t3.left=null;
t3.right=null;
t6.left=null;
t6.right=null;
System.out.println(new LCA().lowestCommonAncestor(t1, t4, t6).val);
}
}
结果: