[LeetCode] Path Sum III 二叉树的路径和之三
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
这道题让我们求二叉树的路径的和等于一个给定值,说明了这条路径不必要从根节点开始,可以是中间的任意一段,而且二叉树的节点值也是有正有负。那么可以用递归来做,相当于先序遍历二叉树,对于每一个节点都有记录了一条从根节点到当前节点到路径,同时用一个变量 curSum 记录路径节点总和,然后看 curSum 和 sum 是否相等,相等的话结果 res 加1,不等的话继续查看子路径和有没有满足题意的,做法就是每次去掉一个节点,看路径和是否等于给定值,注意最后必须留一个节点,不能全去掉了,因为如果全去掉了,路径之和为0,而如果给定值刚好为0的话就会有问题,整体来说不算一道很难的题,参见代码如下:
解法一:
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
int res = ;
vector<TreeNode*> out;
helper(root, sum, , out, res);
return res;
}
void helper(TreeNode* node, int sum, int curSum, vector<TreeNode*>& out, int& res) {
if (!node) return;
curSum += node->val;
out.push_back(node);
if (curSum == sum) ++res;
int t = curSum;
for (int i = ; i < out.size() - ; ++i) {
t -= out[i]->val;
if (t == sum) ++res;
}
helper(node->left, sum, curSum, out, res);
helper(node->right, sum, curSum, out, res);
out.pop_back();
}
};
我们还可以对上面的方法进行一些优化,来去掉一些不必要的计算,可以用 HashMap 来建立路径之和跟其个数之间的映射,即路径之和为 curSum 的个数为 m[curSum],这里需要将 m[0] 初始化为1,后面会讲解原因。在递归函数中,首先判空,若为空,直接返回0。然后就是 curSum 加上当前结点值。由于此时 curSum 可能已经大于了目标值 sum,所以用 curSum 减去 sum,并去 HashMap 中查找这个差值的映射值,若映射值大于0的化,说明存在结束点为当前结点且和为 sum 的路径,这就相当于累加和数组快速求某个区域和的原理。当 curSum 等于 sum 的时候,表明从根结点到当前结点正好是一条符合要求的路径,此时 res 应该大于0,这就是为啥要初始化 m[0] 为1的原因,举个例子来说吧,看下面这棵树:
/ /
假设 sum=3,当遍历根结点1时,curSum 为1,那么 curSum-sum=-2,映射值为0,然后建立映射 m[1]=1。此时遍历结点2,curSum 为3,那么 curSum-sum=0,由于 m[0] 初始化为1,所以 res=1,这是 make sense 的,因为存在和为3的路径。此时再遍历到第二个结点1,curSum 为4,那么 curSum-sum=1,由于之前建立了 m[1]=1 的映射,所以当前的 res 也为1,因为存在以第二个结点1为结尾且和为3的路径,那么递归返回到结点2时候,此时的 res 累加到了2,再返回根结点1时,res 就是2,最终就返回了2,那么可以看出递归函数的意义,某个结点的递归函数的返回值就是该结点上方或下方所有和为 sum 的路径总个数,参见代码如下:
解法二:
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
unordered_map<int, int> m;
m[] = ;
return helper(root, sum, , m);
}
int helper(TreeNode* node, int sum, int curSum, unordered_map<int, int>& m) {
if (!node) return ;
curSum += node->val;
int res = m[curSum - sum];
++m[curSum];
res += helper(node->left, sum, curSum, m) + helper(node->right, sum, curSum, m);
--m[curSum];
return res;
}
};
下面这种方法非常的简洁,用了两个递归函数,其中的一个 sumUp 递归函数是以当前结点为起点,和为 sum 的路径个数,采用了前序遍历,对于每个遍历到的节点进行处理,维护一个变量 pre 来记录之前路径之和,然后 cur 为 pre 加上当前节点值,如果 cur 等于 sum,那么返回结果时要加1,然后对当前节点的左右子节点调用递归函数求解,这是 sumUp 递归函数。而在 pathSum 函数中,我们对当前结点调用 sumUp 函数,加上对左右子结点调用 pathSum 递归函数,三者的返回值相加就是所求,参见代码如下:
解法三:
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if (!root) return ;
return sumUp(root, , sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
int sumUp(TreeNode* node, int pre, int& sum) {
if (!node) return ;
int cur = pre + node->val;
return (cur == sum) + sumUp(node->left, cur, sum) + sumUp(node->right, cur, sum);
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/437
类似题目:
参考资料:
https://leetcode.com/problems/path-sum-iii/
https://leetcode.com/problems/path-sum-iii/discuss/91889/Simple-Java-DFS
https://leetcode.com/problems/path-sum-iii/discuss/91878/17-ms-O(n)-java-Prefix-sum-method
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Path Sum III 二叉树的路径和之三的更多相关文章
- [LeetCode] Path Sum IV 二叉树的路径和之四
If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digit ...
- [LeetCode] Path Sum II 二叉树路径之和之二
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [LeetCode] 666. Path Sum IV 二叉树的路径和 IV
If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digit ...
- [LeetCode] 113. Path Sum II ☆☆☆(二叉树所有路径和等于给定的数)
LeetCode 二叉树路径问题 Path SUM(①②③)总结 Path Sum II leetcode java 描述 Given a binary tree and a sum, find al ...
- LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)
Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence ...
- [Leetcode] Binary tree maximum path sum求二叉树最大路径和
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...
- Leetcode: Path Sum III
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- 【easy-】437. Path Sum III 二叉树任意起始区间和
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...
- 【easy】437. Path Sum III 二叉树任意起始区间和
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...
随机推荐
- 父页面操作iframe子页面的安全漏洞及跨域限制问题
一.父子交互的跨域限制 同域情况下,父页面和子页面可以通过iframe.contentDocument或者parent.document来交互(彼此做DOM操作等,如父页面往子页面注入css). 跨域 ...
- js实现StringBuffer
实现 function StringBuffer() { this.__strings__ = []; }; StringBuffer.prototype.Append = function (str ...
- 前端开发:面向对象与javascript中的面向对象实现(一)
前端开发:面向对象与javascript中的面向对象实现(一) 前言: 人生在世,这找不到对象是万万不行的.咱们生活中,找不到对象要挨骂,代码里也一样.朋友问我说:“嘿,在干嘛呢......”,我:“ ...
- C#递归解决汉诺塔问题(Hanoi)
using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace MyExamp ...
- C#开发微信门户及应用(23)-微信小店商品管理接口的封装和测试
在上篇<C#开发微信门户及应用(22)-微信小店的开发和使用>里面介绍了一些微信小店的基础知识,以及对应的对象模型,本篇继续微信小店的主题,介绍其中API接口的封装和测试使用.微信小店的相 ...
- 提交本地项目到github服务器
已经完成的本地项目 提交到github 并不是按照先在github上创建一个仓库 然后clone下来的顺序 1.在github上创建仓库 2.在本地项目初始化git仓库 $ git init 3.添加 ...
- javaScript基础语法(上)
相关理论概念: 直接量的概念:直接描述某个(些)存储空间的值的量,如变量的值.对象的值.数组的值. 数据类型:在数据结构中的定义是一个值的集合以及定义在这个值集上的一组操作. 1.变量的声明和使用 变 ...
- 1、开篇:公司管理经验谈 - CEO之公司管理经验谈
作为一家IT公司的CEO,我很高兴与大家通过博文的方式进行沟通交流.一方面能够将自己的成长之路以博文的方式记录下来,另一方面是能够与大家交朋友,与大家沟通公司管理方面的知识和经验. 首先,笔者在200 ...
- UDAD 用户故事驱动的敏捷开发 – 演讲实录
敏捷发展到今天已经在软件行业得到了广泛认可,但大多数敏捷方法都是为了解决某一特定问题而总结出来的特定方法或实践,一直缺乏一个可以将整个开发过程串接起来的成体系的方法.用户故事驱动的敏捷开发(User ...
- 原创 C++作用域 (一)
1概述 在所有的计算机程序中,一个基本的目标是操作一些数据,然后获得一些结果.为了操作这些数据,需要为这些数据分配一段内存,我们可以将这段内存称为变量.为了方便操作,以及程序可读性方面的考虑,需要使用 ...