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的更多相关文章

  1. 【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 ...

  2. 【LeetCode OJ】Two Sum

    题目:Given an array of integers, find two numbers such that they add up to a specific target number. T ...

  3. 【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 ...

  4. 【LeetCode OJ】Triangle

    Problem Link: http://oj.leetcode.com/problems/triangle/ Let R[][] be a 2D array where R[i][j] (j < ...

  5. 【LeetCode OJ】Interleaving String

    Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...

  6. 【LeetCode OJ】Reverse Words in a String

    Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...

  7. 【LeetCode OJ】Sum Root to Leaf Numbers

    # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self ...

  8. 【LeetCode OJ】Word Ladder II

    Problem Link: http://oj.leetcode.com/problems/word-ladder-ii/ Basically, this problem is same to Wor ...

  9. 【LeetCode OJ】Word Ladder I

    Problem Link: http://oj.leetcode.com/problems/word-ladder/ Two typical techniques are inspected in t ...

随机推荐

  1. print函数

    python中print既可以写成print a,也可以写成print(a) >>> a=1 >>> print a 1 >>> print(a) ...

  2. 2016年12月17日 星期六 --出埃及记 Exodus 21:12

    2016年12月17日 星期六 --出埃及记 Exodus 21:12 "Anyone who strikes a man and kills him shall surely be put ...

  3. zabbix通过API创建交换机模板,ifAdminStatus;ifOperStatus;ifInUcastPkts;ifAlias

    最终效果: 目的:         通过zabbix的Latest data查看主机就可以看到其监控结果. 监控项:         # 管理状态          IF-MIB::ifAdminSt ...

  4. Mysql新知识点150928

    1.select distinct(DATE_FORMAT(updatetime,'%Y-%m')) as updatetime from barcode where pid!=0 order by ...

  5. Chrome浏览器快捷键大全(新加了其他一些浏览器的独有)

    官方快捷键文档: https://support.google.com/chrome/answer/157179?hl=zh-Hans&ref_topic=14676   浏览器标签页和窗口快 ...

  6. zookeeper第二课 客户端的简单命令

    zookeeper的每个节点既可以是目录也可以是文件,节点上只存一些协调数据(状态.配置.位置),单位一般是KB,大部分数据用sdfs上 只有持久化的节点才可以有子节点,临时节点不可以有自子节点. 客 ...

  7. js原生实现淡入淡出

         转自http://kb.cnblogs.com/page/90854/ 参数说明: fadeIn()与fadeOut()均有三个参数,第一个是事件, 必填; 第二个是淡入淡出速度, 正整数, ...

  8. Java远程调试代码不一致问题汇总

    欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://g ...

  9. mysql数据库与oracle数据库的切换

    1.从mysql数据库中导出ambition(数据库名)结构和数据的ambition.sql文件. 2.将ambition.sql用Power Designer转换成mysql数据模型. 给模型起个名 ...

  10. 1017作业:配置java环境,学习流程图