当前位置:网站首页>二叉树专题--AcWing 47. 二叉树中和为某一值的路径(前序遍历)
二叉树专题--AcWing 47. 二叉树中和为某一值的路径(前序遍历)
2022-07-02 07:21:00 【Morgannr】

题意:
输入一棵二叉树和一个整数,打印出 二叉树中结点值的和 为 输入整数 的 所有路径。
从 树的根结点 开始 往下一直到叶结点 所经过的结点 形成一条路径。
保证树中结点值 均不小于 0。
思路:
从上往下遍历,当遍历到叶子节点的时候,判断当前路径权值和是否等于目标值。
若是,则将答案记录。
若不是,则不进行操作
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {
}
* };
*/
class Solution {
public:
//将 答案数组 ans 定为类中的全局变量,这样记录答案就比较方便。
vector<vector<int>> res;
vector<int> tmp;
vector<vector<int>> findPath(TreeNode* root, int sum) {
if(!root) return res;
dfs(root, 0, sum);
return res;
}
void dfs(TreeNode* rt, int sm, int sum)
{
if (sm > sum) return ;
tmp.push_back(rt->val);//前序遍历,根左右,先进向量
sm += rt->val;
if (!rt->left && !rt->right)//叶子结点
{
if (sm == sum)
{
res.push_back(tmp);
}
}
//前序遍历,上面遍历完根节点之后才递归处理左、右儿子
if (rt->left) dfs(rt->left, sm, sum);
if (rt->right) dfs(rt->right, sm, sum);
//由于还要遍历其它分支,因此还要恢复现场
tmp.pop_back();
sm -= rt->val; //其实不用管,sum传进来的是标量,不是地址
}
};
边栏推荐
- Shapiro Wilk normal analysis by SPSS
- Record attributeerror: 'nonetype' object has no attribute 'nextcall‘
- 13.信号量临界区保护
- LabVIEW为什么浮点数会丢失精度
- 【ARK UI】HarmonyOS ETS的启动页的实现
- 2022-06-17
- UWA report uses tips. Did you get it? (the fourth bullet)
- 快应用中实现自定义抽屉组件
- Ks009 implement pet management system based on SSH
- 如何使用IDE自动签名调试鸿蒙应用
猜你喜欢

618再次霸榜的秘密何在?耐克最新财报给出答案
![[visual studio] visual studio 2019 community version cmake development environment installation (download | install relevant components | create compilation execution project | error handling)](/img/9f/4265f1e3927fcf66602f0fc9e7a9d9.jpg)
[visual studio] visual studio 2019 community version cmake development environment installation (download | install relevant components | create compilation execution project | error handling)

JSP webshell free -- the basis of JSP

Flutter环境配置保姆级教程,让doctor一绿到底

JSP webshell免杀——webshell免杀

《MySQL 8 DBA基础教程》简介

14. Code implementation of semaphore

Hdu1228 a + B (map mapping)

Flink calculates topn hot list in real time

12.进程同步与信号量
随机推荐
PCL point cloud to depth image
Filtering of PCL
LeetCode+ 76 - 80 暴搜专题
JSP webshell免杀——JSP的基础
2.hacking-lab脚本关[详细writeup]
Dialogue Wu Gang: why do I believe in the rise of "big country brands"?
点云投影图片
6种单例模式的实现方式
MYSQL关键字
Lunix reallocates root and home space memory
Introduction to MySQL 8 DBA foundation tutorial
02-taildir source
Analysis of hot spots in AI technology industry
session-cookie与token
华为联机对战服务玩家掉线重连案例总结
【快应用】Win7系统使用华为IDE无法运行和调试项目
Set the playback speed during the playback of UOB equipment
【AppLinking实战案例】通过AppLinking分享应用内图片
Pywin32 opens the specified window
nodejs+express+mysql简单博客搭建