通过一次遍历找到两个节点的位置并且返回最近的祖先节点,只需要通过后序遍历就行。先算出来左、右子树的结果,然后再根据条件判断。
可以约定递归遍历的时候返回 null 就代表这棵子树里没有目标的节点。
所以总共有四种情况:
- 左
null; 右null; 返回 null - 左有值; 右
null; 返回左 - 左
null; 右有值 ; 返回右 - 左有值; 右有值; 返回自己
代码如下:
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;
}