代码随想录算法训练营 | 博客打卡
leetcode 235. 二叉搜索树的最近公共祖先
注:仅为个人笔记,难以细致且通俗。
解决本问题的核心想法:从上向下递归遍历,首次遇到在qp区间内的节点就是pq的公共祖先
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root.Val > p.Val && root.Val > q.Val {
return lowestCommonAncestor(root.Left, p, q)
} else if root.Val < p.Val && root.Val < q.Val {
return lowestCommonAncestor(root.Right, p, q)
} else {
return root
}
}