【路飞】二叉搜索树的最近公共祖先

80 阅读1分钟

题目:二叉搜索树的最近公共祖先

image.png

分析

  1. 如果节点p或者q只有一个存在于树中,那么最近的公共祖先就是存在的那个节点;
  2. 如果节点p和q都不存在于树中,那么直接返回null;
  3. 如果节点p和q都存在于树中,通过后序遍历的方式(从下往上遍历),第一次相交的节点就是最近公共祖先;
function lowestCommonAncestor(root, p, q) {
  if (!root) return null;
  if (root == p || root == q) return root;
  const left = lowestCommonAncestor(root.left, p, q);
  const right = lowestCommonAncestor(root.right, p, q);
  if (left == null && right == null) {
    return null;
  }
  // 后序遍历找到的第一个公共节点
  if (left && right) {
    return root;
  }
  return left || right;
}