【刷算法】LeetCode.236- 二叉树的最近公共祖先

228 阅读1分钟
示例 1:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
示例 2:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
 

说明:

所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉树中。
/**
 * 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(r, a, b) {
  if(r === null || r === a || r === b)
    return r;
  
  let left = lowestCommonAncestor(r.left, a, b);
  let right = lowestCommonAncestor(r.right, a, b);
  
  if(left !== null && right !== null) 
    return r;
  
  return left !== null ? left : right;
};