题目:
解决:递归
递归找两个节点,找到则返回该节点
如果该节点是两个节点的以外节点,对于当前节点的左右继续找,
如果左右均不为空,说明在该节点两边,应返回该节点,
如果仅有一个不为空,说明两节点在同一边,返回不为空的节点
如果都为空,说明这个节点的所在分支没有这两个节点,返回空。
代码:
public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
// write code here
TreeNode p = parent(root,o1,o2);
return p.val;
}
public static TreeNode parent(TreeNode root,int o1,int o2){
if(root==null)
return null;
if(root.val==o1||root.val==o2)
return root;
TreeNode l = parent(root.left,o1,o2);
TreeNode r = parent(root.right,o1,o2);
if(l!=null&&r!=null)
return root;
if(l!=null)
return l;
if(r!=null)
return r;
return null;
}