题目为 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。
思路为深度遍历,最近的公共祖先就是左右两个子树都分别存在符合节点。函数返回值为存在对应节点返回对应值,不存在和不是父节点返回空 ,代码如下
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
if (root==null)
{
return null;
}
if (root==q||root==p)
{
return root;
}
TreeNode l = LowestCommonAncestor(root.left, p, q);
TreeNode r = LowestCommonAncestor(root.right, p, q);
if (l!=null&&r!=null)
{
return root;
}
return l != null ? l : r != null ? r : null;
}