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. html5 svg动画

    http://www.zhangxinxu.com/sp/svg/ 以上是svg的一个线上编辑器,也可以adobe Illustrator制作生成. 我们通过以上编辑器可以获得以下代码. 例: < ...

  2. c语言头文件中定义全局变量的问题

    c语言头文件中定义全局变量的问题 (转http://www.cnblogs.com/Sorean/) 先说一下,全局变量只能定义在 函数里面,任意函数,其他函数在使用的时候用extern声明.千万不要 ...

  3. Working with Binary Data in Python

    http://www.devdungeon.com/content/working-binary-data-python

  4. gitlab open ssl

    cd /home/git/gitlab/ sudo -u git -H vi config/gitlab.yml sudo -u git -H vi /home/git/gitlab-shell/co ...

  5. webform简单控件

    表单元素: 文本类: text password textarea hidden text,password,textarea实现控件:textbox   textmode属性选择password或m ...

  6. 客户端判断是否为IE9以上版本

    function detectBrowser() { var browser = navigator.appName if(navigator.userAgent.indexOf("MSIE ...

  7. go文件操作大全

    参考Go官方库的文件操作分散在多个包中,比如os.ioutil包,我本来想写一篇总结性的Go文件操作的文章,却发现已经有人2015年已经写了一篇这样的文章,写的非常好,所以我翻译成了中文,强烈推荐你阅 ...

  8. APP自动化测试中Monkey和 MonkeyRunner

    在设计了测试用例并通过评审之后,由测试人员根据测试用例中描述的规程步步执行测试,得到实际结果与期望结果的比较.在此过程中,为了节省人力.时间或硬件资源,提高测试效率,便引入了自动化测试的概念.自动化测 ...

  9. jq 实现发送验证码倒计时功能

    var util = { wait:60, hsTime: function (that) { _this = this; if (_this.wait == 0) { $('#hsbtn').rem ...

  10. DOM遍历方法

    为标题行添加样式 $(document).ready(function(){ $('th').parent().addClass('table-heading'); $('tr:not([th]):o ...