作者: 负雪明烛
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:

  1. root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
  2. 10
  3. / \
  4. 5 -3
  5. / \ \
  6. 3 2 11
  7. / \ \
  8. 3 -2 1
  9. Return 3. The paths that sum to 8 are:
  10. 1. 5 -> 3
  11. 2. 5 -> 2 -> 1
  12. 3. -3 -> 11

题目大意

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

解题方法

DFS + DFS

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

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int pathSum(TreeNode root, int sum) {
  12. if(root == null){
  13. return 0;
  14. }
  15. return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
  16. }
  17. public int dfs(TreeNode root, int sum){
  18. int res = 0;
  19. if(root == null){
  20. return res;
  21. }
  22. if(root.val == sum){
  23. res++;
  24. }
  25. res += dfs(root.left, sum - root.val);
  26. res += dfs(root.right, sum - root.val);
  27. return res;
  28. }
  29. }

python代码如下:

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def pathSum(self, root, sum):
  9. """
  10. :type root: TreeNode
  11. :type sum: int
  12. :rtype: int
  13. """
  14. if not root: return 0
  15. return self.dfs(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
  16. def dfs(self, root, sum):
  17. res = 0
  18. if not root: return res
  19. sum -= root.val
  20. if sum == 0:
  21. res += 1
  22. res += self.dfs(root.left, sum)
  23. res += self.dfs(root.right, sum)
  24. return res

BFS + DFS

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

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def pathSum(self, root, sum):
  9. """
  10. :type root: TreeNode
  11. :type sum: int
  12. :rtype: int
  13. """
  14. res = [0]
  15. que = collections.deque()
  16. que.append(root)
  17. while que:
  18. node = que.popleft()
  19. if not node:
  20. continue
  21. self.dfs(node, res, 0, sum)
  22. que.append(node.left)
  23. que.append(node.right)
  24. return res[0]
  25. def dfs(self, root, res, path, target):
  26. if not root: return
  27. path += root.val
  28. if path == target:
  29. res[0] += 1
  30. self.dfs(root.left, res, path, target)
  31. 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. Oracle-创建新表,创建备份表,对表中插入多条数据

    一.创建新表 0.基本语法 create table 表名称(id varchar2(50) primary key ,name char(200) not null,phone number(11) ...

  2. Linux 软件安装位置选择指南

    Linux 软件安装   Linux 下安装软件不像 Windows 下安装这么简单,Windows 下会自动选择合适安装路径,而 Linux 下安装路径大部分完全由自己决定,我可以将软件安装到任意可 ...

  3. UE4之Slate: SImage

    概述 距离上次记录<UE4之Slate:纯C++工程配置>后已经好长时间了: 这个随笔来记录并分享一下SImage控件的使用,以在屏幕上显示一张图片: 目标 通过SImage控件的展示,学 ...

  4. javascript的事件循环机制

    JavaScript是一门编程语言,既然是编程语言那么就会有执行时的逻辑先后顺序,那么对于JavaScript来说这额顺序是怎样的呢? 首先我们我们需要明确一点,JavaScript是单线程语言.所谓 ...

  5. 游戏案例|Service Mesh 在欢乐游戏的应用演变和实践

    作者 陈智伟,腾讯 12 级后台专家工程师,现负责欢乐游戏工作室公共后台技术研发以及团队管理工作.在微服务分布式架构以及游戏后台运维研发有丰富的经验. 前言 欢乐游戏工作室后台是分布式微服务架构,目前 ...

  6. day9 文件处理

    day09 文件处理 一.注册与登录功能 username = input('请输入您的密码:').strip() password = input('请输入您的密码:').strip() f = o ...

  7. android Paint 详解

    /**     * Paint类介绍 * * Paint即画笔,在绘图过程中起到了极其重要的作用,画笔主要保存了颜色, * 样式等绘制信息,指定了如何绘制文本和图形,画笔对象有很多设置方法, * 大体 ...

  8. SVN的基本介绍\服务器配置

    ### 1. 工作场景 1. 进入公司需要做的关于开发的第一件事, 就是向项目经理索要SVN服务器地址+用户名+密码### 2. 角色解释> 服务器: 用于存放所有版本的代码,供客户端上传下载更 ...

  9. SpringBoot(1):初始SpringBoot

    一. SpringBoot 简介 1. SpringBoot介绍 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特 ...

  10. 【编程思想】【设计模式】【结构模式Structural】装饰模式decorator

    Python版 https://github.com/faif/python-patterns/blob/master/structural/decorator.py #!/usr/bin/env p ...