【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 ...
随机推荐
- Burning Bridges-ZOJ1588(割边求解)
Burning Bridges Time Limit: 5 Seconds Memory Limit: 32768 KB Ferry Kingdom is a nice little country ...
- 关于使用nuget的部分代码
Install-Package 安装包 -Version 4.3.1 参数指定版本 Uninstall-Package 卸载包 Update-Package 更新包 Get-Package 默认列出本 ...
- [问题2014A10] 解答
[问题2014A10] 解答 考虑如下变形: \[(I_n-A)^2=(AA'-A)(I_n-A)=A(A'-I_n)(I_n-A)=-A(I_n-A)'(I_n-A).\] 因为 \(A\) 是非 ...
- php 中的常量
1.__FINE__ 返回当前常量所在的行号. 2.__FILE__ 返回文件的完整路径和文件名. 3.__FUNCTION__ 返回函数名称. 4.__CLASS__ 返回类名称. 5.__METH ...
- Java与JavaScript的区别
(1)执行方式不同 java:是编译语言,需要先编译再执行 JavaScript:无需编译,直接执行 (2)数据类型不同 java:强数据类型语言 JavaScript:弱数据类型语言 (3)运行位置 ...
- jodaTime 的使用说明
<dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifact ...
- 和Java相关的一些好文章(不定期更新)
1.Java 集合类详解 (包括arraylist,linkedlist,vector,stack,hashmap,hashtable,treemap,collection等). 2.Java 理论与 ...
- runtime运行机制方法学习
runtime这玩意第一次听说时都不知道是什么,经过了解后才知道它就是oc动态语言的机制,没有它那oc就不能称为动态语言.在之前可能大家对runtime了解都不深,随着编程技能的日益加深和需要,大家开 ...
- vs2010打包(带数据库)图文详解
最近刚刚打包发布了用VS2010开发的一个收费系统,借此讲一讲打包过程,供大家参考. 首先打开已经完成的工程,如图: 下面开始制作安装程序包. 第一步:[文件]——[新建]——[项目]——安装项目. ...
- 插件框架(Plugin Framework)
HOW TO MAKE PLUGIN FRAMEWORK 插件系统构建 Dissect Eclipse Plugin Framework