defdfs(node: Optional[TreeNode], s: int) -> None: if node isNone: return nonlocal ans s += node.val ans += cnt[s - targetSum] cnt[s] += 1 dfs(node.left, s) dfs(node.right, s) cnt[s] -= 1# 恢复现场
dfs(root, 0) return ans
236.二叉树的最近公共祖先(中等)
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
涉及知识点
二叉树
解决思路
还是正常的递归,如果左右都找到了,那当前的节点就是目标节点,如果当前节点为p、q,那就没往下讨论的必要了,直接返回当前节点即可。注意最后返回的是left or right即可,比较巧妙。
1 2 3 4 5 6 7 8 9
classSolution: deflowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: if root in (None, p, q): return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: # 左右都找到 return root # 当前节点是最近公共祖先 return left or right