当前位置:网站首页>二叉树专题--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传进来的是标量,不是地址
}
};
边栏推荐
- AI技术产业热点分析
- 02-taildir source
- Mongodb quickly get started with some simple operations of mongodb command line
- Hdu1236 ranking (structure Sorting)
- "Talking about podcasts" vol.352 the age of children: breaking the inner scroll, what can we do before high school?
- Use of vscode tool
- 记录 AttributeError: ‘NoneType‘ object has no attribute ‘nextcall‘
- 14. Code implementation of semaphore
- Sus system availability scale
- 一招快速实现自定义快应用titlebar
猜你喜欢

2022-06-17

Internet News: Tencent conference application market was officially launched; Soul went to Hong Kong to submit the listing application
![2. Hacking lab script off [detailed writeup]](/img/f3/29745761cd5ad4df84c78ac904ea51.png)
2. Hacking lab script off [detailed writeup]

简洁、快速、节约内存的Excel处理工具EasyExcel

Dialogue Wu Gang: why do I believe in the rise of "big country brands"?

Is this code PHP MySQL redundant?

session-cookie与token

From Read and save in bag file Jpg pictures and PCD point cloud

Hdu1236 ranking (structure Sorting)

使用华为性能管理服务,按需配置采样率
随机推荐
JSP webshell免殺——JSP的基礎
Flink submitter
拆解美图SaaS:开着飞机换引擎
PCL extracts a subset from a point cloud
【TS】1368- 秒懂 TypeScript 泛型工具类型!
Lunix reallocates root and home space memory
2022爱分析· 国央企数字化厂商全景报告
Is this code PHP MySQL redundant?
shell编程01_Shell基础
Use WinDbg to statically analyze dump files (summary of practical experience)
PCL之滤波
Disassembling Meitu SaaS: driving the plane to change the engine
《实习报告》Skywalking分布式链路追踪?
Session cookies and tokens
Filtering of PCL
UVM - configuration mechanism
12.进程同步与信号量
PCL projection point cloud
简洁、快速、节约内存的Excel处理工具EasyExcel
js数组常用方法