LeetCode236-二叉树的最近公共祖先
原题链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
相同题:
LeetCode235:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
剑指offer68-I:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/
剑指offer68-II:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/
解题思路:树形DP
代码:
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 # case1: p是q的lca or q是p的lca 9 # case2: p和q不互为lca,都向上遍历找到 10 class Solution: 11 def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 12 # base case 13 if not root or root == p or root == q: 14 return root 15 left = self.lowestCommonAncestor(root.left, p, q) 16 right = self.lowestCommonAncestor(root.right, p, q) 17 # 命中case2,不命中case1 18 if left and right: 19 return root 20 # 命中case1,不命中case2 21 if left: 22 return left 23 else: 24 return right