-
代码:
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 or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if not left: return right if not right: return left return root
-
思路:后序遍历DFS,参考这位大神的思路
LeetCode236 二叉树的最近公共祖先
最新推荐文章于 2023-04-01 18:32:46 发布