题目:二叉搜索树的最近公共祖先
分析
- 如果节点p或者q只有一个存在于树中,那么最近的公共祖先就是存在的那个节点;
- 如果节点p和q都不存在于树中,那么直接返回null;
- 如果节点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;
}