# 236. 二叉树的最近公共祖先

# 题目

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

# 题解

# 递归

/**
 * 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.val == p.val || root.val == q.val) return root;
  let left = lowestCommonAncestor(root.left, p, q);
  let right = lowestCommonAncestor(root.right, p, q);
  if (left && right) return root;
  return left || right;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20