# 剑指offer68 - II 二叉树的最近公共祖先

# 思路
由于lowestCommonAncestor(root, p, q)的功能是找出以root为根节点的两个节点p和q的最近公共祖先。 我们考虑:
如果p和q分别是root的左右节点,那么root就是我们要找的最近公共祖先
如果root是None,说明我们在这条寻址线路没有找到,我们返回None表示没找到
我们继续在左右子树执行相同的逻辑。
如果左子树没找到,说明在右子树,我们返回lowestCommonAncestor(root.right, p , q)
如果右子树没找到,说明在左子树,我们返回lowestCommonAncestor(root.left, p , q)
如果左子树和右子树分别找到一个,我们返回root
# 代码
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
    if(!root || root === p || root === q) return root;
    const left = lowestCommonAncestor(root.left,p,q)
    const right = lowestCommonAncestor(root.right,p,q)
    if(!left) return right // 左子树找不到返回右子树
    if(!right) return left
    return root
};
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21