应用题-二叉树专题-二叉树的最近公共祖先 ( 需要注意写一下 )

管理员
```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': # p 是 q 的公共祖先 # q 是 p 的公共祖先 # p 和 q 有公共祖先 if not root: return root if root.val == p.val: return root if root.val == q.val: return root node1 = self.lowestCommonAncestor( root.left, p, q ) node2 = self.lowestCommonAncestor( root.right, p, q ) # 根据 node1 和 node2 是否为空来判断到底返回什么 if node1 and not node2: return node1 if node2 and not node1: return node2 if node2 and node1: return root return None ```
评论 1

发表评论 取消回复

Shift+Enter 换行  ·  Enter 发送
HelloWorld
HelloWorld 1 楼 2026-04-07 11:59
```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 找到该树中两个指定节点的最近公共祖先 def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if not root: return root if root == p or root == q: return root x = self.lowestCommonAncestor( root.left, p, q ) y = self.lowestCommonAncestor( root.right, p, q ) if x and y: return root if x: return x if y: return y return None ```