【LeetCode OJ】Path Sum

时间:2022-09-01 21:17:40

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 &lt ...

  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. canvas学习和面向对象(二)

    Canvas 学习(二) 上一篇Canvas 学习(一)中我是用canvas绘制了一些基本和组合的图形. 现在开始绘制图片和动画帧,以及面向对象的升级版本. 还是一样,看代码,所有的代码都托管在git ...

  2. truncate 、delete与drop区别

    原博文地址:http://www.cnblogs.com/8765h/archive/2011/11/25/2374167.html 相同点: 1.truncate和不带where子句的delete. ...

  3. 转载 --ios 模型-setValuesForKeysWithDictionary

    应用场景:app请求后端数据,返回的数据是JSON形式,如: { "is_favor" = 0; "is_follow" = 0; "is_prais ...

  4. 字符串String: 常量池

    2.1          String类 String是不可变类, 即一旦一个String对象被创建, 包含在这个对象中的字符序列是不可改变的, 直至该对象被销毁. String类是final类,不能 ...

  5. java 中多线程和锁的使用

    关键词: implements  实现  Runnable 类 run()  方法 注意点 : 创建类的实例 InterfaceController inter=new InterfaceContro ...

  6. struts2 package元素配置

    package 元素的所有属性及对应功能: Attribute Required Description name yes key to for other packages to reference ...

  7. iOS相机权限、相册权限、定位权限判断

    1.判断用户是否有权限访问相册 #import <AssetsLibrary/AssetsLibrary.h> ALAuthorizationStatus author = [ALAsse ...

  8. C&num;数组--&lpar;一维数组,二维数组的声明,使用及遍历&rpar;

    数组:是具有相同数据类型的一组数据的集合.数组的每一个的变量称为数组的元素,数组能够容纳元素的数称为数组的长度. 一维数组:以线性方式存储固定数目的数组元素,它只需要1个索引值即可标识任意1个数组元素 ...

  9. LAS(Listener、Attender、Speller)端到端构架

    基于注意力(Attention)机制的端到端系统,又被称为LAS端到端构架. [6] W. Chan, N. Jaitly, Q. Le, O. Vinyals. Listen, Attend and ...

  10. 你所不了解的javascript操作DOM的细节知识点&lpar;一&rpar;

    你所不了解的javascript操作DOM的细节知识点(一) 一:Node类型 DOM1级定义了一个Node接口,该接口是由DOM中的所有节点类型实现.每个节点都有一个nodeType属性,用于表明节 ...