面试题 04.08. 首个共同祖先

133 阅读1分钟

题目描述

leetcode-cn.com/problems/fi…

分析

要解决这道题,需要彻底弄明白怎么找这两个节点的最近公共祖先

算法

递归

过程

在递归过程中,查找当前 root 是否为 pq,以及是否两节点在左,右树中

对于一个 node

如果两节点分别在左右树中,很显然最近的 parent 就是 node

如果它本身就是其中一个,返回他作为备选答案

如果没有节点了,返回 null

代码

/**
 * 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) {
  // return the LCA, if no LCA exists, return null

  // if traversed node is null, return null because empty tree doesn't contain p or q
  if (!root) return

  // if traversed node is p or q, the LCA is p, q or some node above
  // which means it cannot be some node below
  // so return the traversed node root
  if (root === q || root === p) return root

  const left = lowestCommonAncestor(root.left, p, q)
  const right = lowestCommonAncestor(root.right, p, q)

  // left and right all have results, meaning that p and q locate at both left and right
  if (left && right) return root

  // only one has result, meaning that p and q all locate at one side of tree
  // both undefined, meaning p and q are not locate at the tree, return null
  return l || r
}