【LeetCode OJ】Path Sum
Problem Link:
http://oj.leetcode.com/problems/path-sum/
One solution is to BFS the tree from the root, and for each leaf we check if the path sum equals to the given sum value.
The code is as follows.
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
"""
BFS from the root to leaves.
For each leaf, check the path sum with the target sum
"""
if not root:
return False
q = [(root,0)]
while q:
new_q = []
for n, s in q:
s += n.val
# If n is a leaf, check the path-sum with the given sum
if n.left == n.right == None:
if sum == s:
return True
else: # Continue BFS
if n.left:
new_q.append((n.left,s))
if n.right:
new_q.append((n.right,s))
q = new_q
return False
The other solution is to DFS the tree, and do the same check for each leaf node.
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
"""
DFS from the root to leaves.
For each leaf, check the path sum with the target sum
"""
# Special case
if not root:
return False
# Record the current path
path = [root]
# The path sum of the current path
current_sum = root.val
# Hash set for keeping visited nodes
visited = set()
# Start DFS
while path:
node = path[-1]
# Touch the leaf node
if node.left == node.right == None:
if sum == current_sum:
return True
current_sum -= node.val
path.pop()
else:
if node.left and node.left not in visited:
# Go deeper to the left
visited.add(node.left)
path.append(node.left)
current_sum += node.left.val
elif node.right and node.right not in visited:
# Go deeper to the right
visited.add(node.right)
path.append(node.right)
current_sum += node.right.val
else:
# Go back to the upper level
current_sum -= node.val
path.pop()
return False
【LeetCode OJ】Path Sum的更多相关文章
- 【LeetCode OJ】Path Sum II
Problem Link: http://oj.leetcode.com/problems/path-sum-ii/ The basic idea here is same to that of Pa ...
- 【LeetCode OJ】Two Sum
题目:Given an array of integers, find two numbers such that they add up to a specific target number. T ...
- 【LeetCode OJ】Binary Tree Maximum Path Sum
Problem Link: http://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ For any path P in a bina ...
- 【LeetCode OJ】Triangle
Problem Link: http://oj.leetcode.com/problems/triangle/ Let R[][] be a 2D array where R[i][j] (j < ...
- 【LeetCode OJ】Interleaving String
Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...
- 【LeetCode OJ】Reverse Words in a String
Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...
- 【LeetCode OJ】Sum Root to Leaf Numbers
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self ...
- 【LeetCode OJ】Word Ladder II
Problem Link: http://oj.leetcode.com/problems/word-ladder-ii/ Basically, this problem is same to Wor ...
- 【LeetCode OJ】Word Ladder I
Problem Link: http://oj.leetcode.com/problems/word-ladder/ Two typical techniques are inspected in t ...
随机推荐
- webapi 解决ajax跨域请求问题
webapi在配置文件中加入这几句就可以解决ajax(同源策略是JavaScript里面的限制,其他的编程语言,比如在C#,Java或者iOS等其他语言中是可以调用外部的WebService,也就是 ...
- Entity Framework 第十篇 条件查询
业务类中 我们根据条件来动态的查询 创建IQueryable接口 public IQueryable<TEntity> GetQueryable() { IQueryable<TEn ...
- HDU Coprime
Coprime Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total S ...
- 【C++/Qt】Qt中的parent形参
在 派生类的构造函数初始化列表中 调用 父类的带有参数的构造函数,是为了初始化从父类继承来的成员变量.因为这些变量无法直接初始化,只能采用这种方式初始化. 而在qt中,MainWindow中的某成员变 ...
- VS下的解决方案目录结构设置和管理
转载:http://blog.csdn.net/pl20140910/article/details/52074165 为了方便管理自己写的代码,也为了日后工作能方便的查找之前做过相同的代码,仿照某源 ...
- SQL Server书籍整理
1.<Microsoft SQL Server企业级平台管理实践>徐海蔚2.<SQL Server 2005 Performance Tuning性能调校>胡百敬3.<M ...
- C#读取XML文件中有乱码的处理办法
1.以文本的方式读取出xml内容 2.如果xml加载文本失败,替换掉乱码的内容 private static void loadxml(XmlDocument doc, string str) { t ...
- 一个webpack,react,less,es6的DEMO
1.package.json如下 { "name": "demo", "version": "1.0.0", " ...
- css取消input、select默认样式(手机端)
IOS端: background-color:transparent; border-color:transparent; andorid端: 仅仅使用上面的代码还不够,可以发现select框在某些浏 ...
- ~是什么意思 在C语言中,~0代表什么
是c语言中的位运算符:取反.0在内存中的存储方式是所有位为0,0000000000000000那么按位取反后位16个1(如果整形在你的机器上站16位),那么表示的数为-1.