【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 ...
随机推荐
- 开源.NET FTP组件edtFTPnet 用法
edtFTPnet官方网站:http://www.enterprisedt.com/products/edtftpnet/ 目前最新版本为2.2.3,下载后在bin目录中找到edtFTPnet.dll ...
- Android Studio build dex jar
Gradle配置 Build配置文件gradle.build中添加如下task task clearJar(type: Delete) { delete 'build/outputs/mylib.ja ...
- webform简单控件
表单元素: 文本类: text password textarea hidden text,password,textarea实现控件:textbox textmode属性选择password或m ...
- openfire聊天消息记录插件关键代码
package com.sqj.openfire.chat.logs; import java.io.File; import java.util.Date; import java.util.Lis ...
- python mysql操作
引入数据库的包 import MySQLdb 连接数据库conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='te ...
- Python3.X新特性之print和exec
print print 现在是一个函数,不再是一个语句.<语法更为清晰> 实例1 打开文件 log.txt 以便进行写入并将对象指定给 fid.然后利用 print将一个字符串重定向给文件 ...
- html中button自动提交表单?
在ie中,button默认的type是button,而其他浏览器和W3C标准中button默认的属性都是submit
- remount failed: Operation not permitted ,怎么办呢?
remount failed: Operation not permitted ,怎么办呢? 1. 确定是否正确连接手机了$ adb devices 2. 进入shell$ adb shell 3. ...
- 《高级Web应用程序设计》课程学习资料
任务1:什么是ASP.NET MVC 1.1 ASP.NET MVC简介 1.2 认识ASP.NET MVC项目结构 1.3 ASP.NET MVC生命周期 任务2:初识ASP.NET MVC项目开 ...
- Find a point on a 'line' between two Vector3
Find a point on a 'line' between two Vector3http://forum.unity3d.com/threads/find-a-point-on-a-line- ...