#-*- coding: UTF-8 -*-
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
sumList=[]
def dfs(self,root):
curSum=self.sumList[-1]
if root.left!=None or root.right!=None:self.sumList.pop()
else:return
if root.left!=None:
valsum=curSum+root.left.val
self.sumList.append(valsum)
self.dfs(root.left)
if root.right!=None:
valsum=curSum+root.right.val
self.sumList.append(valsum)
self.dfs(root.right)
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
self.sumList=[]
if root==None:return False
else:
self.sumList.append(root.val)
self.dfs(root)
if self.sumList.__contains__(sum):
return True
return False
相关文章
- Leetcode Minimum Path Sum
- [LeetCode&Python] Problem 371. Sum of Two Integers
- 二叉树系列 - 二叉树里的最长路径 例 [LeetCode] Binary Tree Maximum Path Sum
- 【LeetCode】377. Combination Sum IV 解题报告(Python & C++)
- 【LeetCode】216. Combination Sum III 解题报告(Python & C++)
- 【LeetCode】1020. Partition Array Into Three Parts With Equal Sum 解题报告(Python)
- 【LeetCode】303. Range Sum Query - Immutable 解题报告(Python)
- 【LeetCode】Path Sum II 二叉树递归
- [LeetCode] 113. Path Sum II ☆☆☆(二叉树所有路径和等于给定的数)
- [LeetCode][Python]16: 3Sum Closest