二叉树最近公共祖先 (LeetCode 236)

正在访问
目标 P (6)
目标 Q (4)
返回有效节点
发现 LCA (5)
算法执行日志
function lowestCommonAncestor(root, p, q) {
  if (!root || root == p || root == q) return root;
  let left = lowestCommonAncestor(root.left, p, q);
  let right = lowestCommonAncestor(root.right, p, q);
  if (left && right) return root; // LCA!
  return left ? left : right;
}