[Leetcode] Binary tree--112. Path Sum
来源:互联网 发布:java字符串数组 \0 编辑:程序博客网 时间:2024/06/06 08:28
112. Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
Solution:
1. use iterative way; bfs
1 if root is None: 2 return False 3 d = deque() 4 5 d.append((root, root.val)) 6 7 while(len(d)): 8 nodeInfo = d.popleft() 9 node = nodeInfo[0]10 s = nodeInfo[1]11 if (not node.left) and (not node.right):12 if s == sum:13 return True14 if node.left:15 d.append((node.left, s + node.left.val))16 if node.right:17 d.append((node.right, s + node.right.val))18 return False
2. use recursive way
1 return self.haspathSumHelper(root, 0, sum) 2 3 def haspathSumHelper(self, node, current, sum): 4 5 if node is None: 6 return False 7 current += node.val 8 if (not node.left ) and (not node.right): 9 if current == sum:10 return True11 else:12 return False13 14 15 return self.haspathSumHelper(node.left, current, sum) or self.haspathSumHelper(node.right, current, sum)
阅读全文
0 0
- [Leetcode] Binary tree--112. Path Sum
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 【Leetcode】Binary Tree Maximum Path Sum
- ORACLE ORA-00600: 内部错误代码, 参数: [kokbcvb1]与merge into
- HDU 6103 Kirinriki(尺取法)
- A%BProblem——线性筛素数与前缀和
- Python3 打包成.exe(附IndexError: tuple index out of range错误解决)
- nosql-mongodb
- [Leetcode] Binary tree--112. Path Sum
- 【Ubuntu-Tensorflow】程序结束掉GPU显存没有释放的问题
- 【Python】Anaconda安装包
- 年薪30万-50万,站在风口上的大数据面临150万的人才紧缺
- 大端模式和小端模式详解
- 把英语当成是一门语言去学习
- Google/LintCode:M-合并k个排序链表
- 合并链表
- Retrofit2整理