算法笔记3:二叉树最近公共祖先

85 阅读1分钟

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

通过一次遍历找到两个节点的位置并且返回最近的祖先节点,只需要通过后序遍历就行。先算出来左、右子树的结果,然后再根据条件判断。

可以约定递归遍历的时候返回 null 就代表这棵子树里没有目标的节点。

所以总共有四种情况:

  1. null ; 右 null ; 返回 null
  2. 左有值; 右 null; 返回左
  3. null; 右有值 ; 返回右
  4. 左有值; 右有值; 返回自己

代码如下:

const lowestCommonAncestor = function(root, p, q) {
  if (!root || root.val === p || root.val === q) {
    return root;
  }
  
  const left = lowestCommonAncestor(root.left, p, q);
  const right = lowestCommonAnscestor(root.right, p, q);
  
  if (left !== null && right !== null) {
    return root;
  }
  
  return left === null ? right : left;
}