[关闭]
@Lin-- 2020-02-20T03:44:11.000000Z 字数 630 阅读 331

hasPathSum

Leetcode


变式的路径输出问题

  1. '''
  2. # File: hasPathSum.py
  3. # Author: 0HP
  4. # Date: 20200218
  5. # Purpose: solve the problem in website: https://leetcode.com/problems/path-sum/
  6. '''
  7. # Definition for a binary tree node.
  8. class TreeNode:
  9. def __init__(self, x):
  10. self.val = x
  11. self.left = None
  12. self.right = None
  13. class Solution:
  14. def RecordPath(self,root:TreeNode,sum:int,sumlist:list):
  15. if root==None:
  16. return
  17. sum=sum+root.val
  18. if root.left==None and root.right==None:
  19. sumlist.append(sum)
  20. self.RecordPath(root.left,sum,sumlist)
  21. self.RecordPath(root.right,sum,sumlist)
  22. def hasPathSum(self, root: TreeNode, sum: int) -> bool:
  23. Sum=0
  24. Sumlist=[]
  25. self.RecordPath(root,Sum,Sumlist)
  26. for i in sumlist:
  27. if sum==i:
  28. return True
  29. return False
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注