题解
思路
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
### 1208 后序遍历(88 ms,24.1 MB)
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
# 递归终止条件:若当前节点root为空 或 当前节点root等于p 或 当前节点root等于q
if not root or root == p or root == q: return root
l = self.lowestCommonAncestor(root.left, p, q) # 递归左子树,检查并返回p、q是否在左子树中的情况
r = self.lowestCommonAncestor(root.right, p, q) # 递归右子树,检查并返回p、q是否在右子树中的情况
# if not left and not right: return # 若p、q不在左子树中,则直接返回
if not l: return r # 若p、q不在左子树中,则返回p、q在右子树的情况
if not r: return l # 若p、q不在右子树中,则返回p、q在左子树的情况
return root # 若p、q分别在不同的子树中,则返回当前子树的根节点
- p、q为整型,而非TreeNode