作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/path-sum-iii/#/description

题目描述

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11

题目大意

找到二叉树中从某个顶点向下找的路径中,有多少条等于sum.

解题方法

DFS + DFS

使用DFS解决。dfs函数有两个参数,一个是当前的节点,另一个是要得到的值。当节点的值等于要得到的值的时候说明是一个可行的解。再求左右的可行的解的个数,求和之后是所有的。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int pathSum(TreeNode root, int sum) {
if(root == null){
return 0;
}
return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
} public int dfs(TreeNode root, int sum){
int res = 0;
if(root == null){
return res;
}
if(root.val == sum){
res++;
}
res += dfs(root.left, sum - root.val);
res += dfs(root.right, sum - root.val);
return res;
}
}

python代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
if not root: return 0
return self.dfs(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum) def dfs(self, root, sum):
res = 0
if not root: return res
sum -= root.val
if sum == 0:
res += 1
res += self.dfs(root.left, sum)
res += self.dfs(root.right, sum)
return res

BFS + DFS

使用BFS找到每个顶点作为起点的情况下,用dfs计算等于sum的路径个数。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
res = [0]
que = collections.deque()
que.append(root)
while que:
node = que.popleft()
if not node:
continue
self.dfs(node, res, 0, sum)
que.append(node.left)
que.append(node.right)
return res[0] def dfs(self, root, res, path, target):
if not root: return
path += root.val
if path == target:
res[0] += 1
self.dfs(root.left, res, path, target)
self.dfs(root.right, res, path, target)

日期

2017 年 5 月 2 日
2018 年 11 月 20 日 —— 真是一个好天气

【LeetCode】437. Path Sum III 解题报告(Python)的更多相关文章

  1. 47. leetcode 437. Path Sum III

    437. Path Sum III You are given a binary tree in which each node contains an integer value. Find the ...

  2. [LeetCode] 437. Path Sum III 路径和 III

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  3. LeetCode 437. Path Sum III (路径之和之三)

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  4. leetcode 437 Path Sum III 路径和

      相关问题:112 path sum /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNo ...

  5. Leetcode 437. Path Sum III

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  6. LeetCode 437. Path Sum III (STL map前缀和)

    找遍所有路径,特判以根为起点的串即可. 代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * Tr ...

  7. 437. Path Sum III

    原题: 437. Path Sum III 解题: 思路1就是:以根节点开始遍历找到适合路径,以根节点的左孩子节点开始遍历,然后以根节点的右孩子节点开始遍历,不断循环,也就是以每个节点为起始遍历点 代 ...

  8. 【LeetCode】113. Path Sum II 解题报告(Python)

    [LeetCode]113. Path Sum II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fu ...

  9. 【leetcode】437. Path Sum III

    problem 437. Path Sum III 参考 1. Leetcode_437. Path Sum III; 完

随机推荐

  1. 【Python小试】判断一条序列GC含量高低

    题目: 随便给定一条序列,如果GC含量超过65%,则认为高. 编程: from __future__ import division #整数除法 def is_gc_rich(dna): length ...

  2. pyyaml模块

    pyyaml模块是一种文件数据处理格式的方法,常用与生成.解析或修改.yaml配置文件 1.常见.yaml文件格式内容如下 languages: - Ruby - Perl - Python webs ...

  3. 2 — springboot的原理

    1.初步探索:第一个原理:依赖管理 发现:这里面存放着各种jar包 和 版本号 这也是:我们在前面第一个springboot项目创建中勾选了那个web,然后springboot就自动帮我们导入很多东西 ...

  4. Spark(十六)【SparkStreaming基本使用】

    目录 一. SparkStreaming简介 1. 相关术语 2. SparkStreaming概念 3. SparkStreaming架构 4. 背压机制 二. Dstream入门 1. WordC ...

  5. jvm的优化

    a) 设置参数,设置jvm的最大内存数 b) 垃圾回收器的选择

  6. GO 时间处理

    比较大小 比较大小 先把当前时间格式化成相同格式的字符串,然后使用time的Before, After, Equal 方法即可. time1 := "2015-03-20 08:50:29& ...

  7. Linux学习 - ACL权限

    一.ACL权限简介 ACL权限是为了防止权限不够用的情况,一般的权限有所有者.所属组.其他人这三种,当这三种满足不了我们的需求的时候就可以使用ACL权限 二.ACL权限开启 1 查看当前系统分区 df ...

  8. Hadoop生态圈学习-1(理论基础)

    一.大数据技术产生的背景 1. 计算机和信息技术(尤其是移动互联网)的迅猛发展和普及,行业应用系统的规模迅速扩大(用户数量和应用场景,比如facebook.淘宝.微信.银联.12306等),行业应用所 ...

  9. 使用jsp制作index,可以通过<c:if test==“管理员”>或<c:if test=="客户">来区别展示用户界面

    <%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ ta ...

  10. mybatis联合查询

    1.有学生实体 @Component @Scope("prototype") public class StudentInfo { private Integer studentI ...