LeetCode236. 二叉树的最近公共祖先
- 题目链接
- 代码
题目链接
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Noneclass Solution:def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':if root is None or root == p or root == q:return rootleft = self.lowestCommonAncestor(root.left, p, q)right = self.lowestCommonAncestor(root.right, p, q)if left is not None and right is not None:return rootif left is None and right is not None:return rightif left is not None and right is None:return leftelse:return None