150强访谈简单

BST 的最低共同祖先

“BST 最低共同祖先”问题的详细指南和 Python 实现。

问题陈述

简单

给定二叉搜索树 (BST),找到 BST 中两个给定节点的最低公共祖先 (LCA) 节点。

根据 LCA 的定义:“最低公共祖先被定义为两个节点 p 和 q 之间的最低公共祖先,作为 T 中同时具有 p 和 q 作为后代的最低节点(其中我们允许一个节点是其自身的后代)。”

BST 被表示为一个级别顺序列表。实现一个函数 lowestCommonAncestor(root: list, p: int, q: int) -> int 返回 LCA 节点的值。

约束条件
  • The number of nodes in the tree is in the range [2, 100000]
  • -1000000000 <= Node.val <= 1000000000
  • All Node.val are unique
  • p != q
  • p and q will exist in the BST

示例

Example 1
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 8
Output
6
Explanation

The LCA of nodes 2 and 8 is 6, which is the root.

Example 2
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 4
Output
2
Explanation

The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself.

Example 3
Input
[2,1], 2, 1
Output
2
Explanation

The LCA of nodes 2 and 1 is 2.

Need a Hint?
考虑使用树特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。