112.路径总和
第一个:
class TreeNode ( object ) :
def __init__ ( self, val= 0 , left= None , right= None ) :
self. val = val
self. left = left
self. right = right
class Solution ( object ) :
def hasPathSum ( self, root, targetSum) :
"""
:type root: Optional[TreeNode]
:type targetSum: int
:rtype: bool
"""
if not root:
return False
if not root. left and not root. right:
return root. val == targetSum
return ( self. hasPathSum( root. left, targetSum - root. val) or
self. hasPathSum( root. right, targetSum - root. val)
Yes
No
Yes
No
开始
根节点为空?
返回 False
是否为叶子节点?
检查路径和是否等于目标值
返回结果
递归检查左子树
递归检查右子树
返回左或右子树的结果
第二个:
def hasPathSum ( self, root, targetSum) :
"""
:type root: Optional[TreeNode]
:type targetSum: int
:rtype: bool
"""
if not root:
return False
Sum_lst = [ ]
def pathsum ( node, current_sum) :
if not node:
return
current_sum += node. val
if not node. left and not node. right:
Sum_lst. append( current_sum)
pathsum( node. left, current_sum)
pathsum( node. right, current_sum)
pathsum( root, 0 )
for path_sum in Sum_lst:
if path_sum == targetSum:
return True
return False
是
否
是
否
Pathsum
是
否
是
否
当前节点是否为空
返回
累加当前节点值
是否为叶子节点
记录路径和
递归左子树
递归右子树
返回
开始
根节点是否为空
返回 False
初始化 Sum_lst
调用 pathsum
遍历 Sum_lst
是否存在等于目标值的路径和
返回 True
返回 False
第三个【最快】:
def hasPathSum ( self, root, targetSum) :
"""
:type root: Optional[TreeNode]
:type targetSum: int
:rtype: bool
"""
if root is None :
return False
return self. traversal( root, targetSum- root. val)
def traversal ( self, root, count) :
"""
检查从根节点到叶节点的路径上,是否存在节点值之和等于给定值的路径。
参数:
root: 树的根节点。
count: 目标节点值之和。
返回:
如果存在一条路径,其节点值之和等于给定值,则返回True;否则返回False。
"""
if ( root. left is None and root. right is None and count == 0 ) :
return True
if ( root. left is None and root. right is None and count != 0 ) :
return False
if root. left:
count -= root. left. val
if self. traversal( root. left, count) :
return True
count += root. left. val
if root. right:
count -= root. right. val
if self. traversal( root. right, count) :
return True
count += root. right. val
return False
flowchart TD
A[开始] --> B{是否为叶节点?}
B -->|是| C{路径和是否为0?}
C -->|是| D[返回True]
C -->|否| E[返回False]
B -->|否| F{是否有左子树?}
F -->|是| G[更新count并递归左子树]
G --> H{左子树是否满足?}
H -->|是| I[返回True]
H -->|否| J[回溯恢复count]
F -->|否| K{是否有右子树?}
K -->|是| L[更新count并递归右子树]
L --> M{右子树是否满足?}
M -->|是| N[返回True]
M -->|否| O[回溯恢复count]
K -->|否| P[返回False]