题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,求一个二叉树中,根节点到叶子节点的最大值是多少。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
ans = False
def dfs(root: Optional[TreeNode], curSum: int) -> None:
if not root:
return
curSum += root.val
if not root.left and not root.right and curSum == targetSum:
nonlocal ans
ans = True
return
dfs(root.left, curSum)
dfs(root.right, curSum)

dfs(root, 0)
return ans