当前位置:网站首页>二叉树专题--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传进来的是标量,不是地址
}
};
边栏推荐
- 华为应用市场应用统计数据问题大揭秘
- Leetcode+ 76 - 80 storm search topic
- 软件产品管理系统有哪些?12个最佳产品管理工具盘点
- UVM——Callback
- 2022-06-17
- In the face of uncertainty, the role of supply chain
- Pywin32打开指定窗口
- Open the encrypted SQLite method with sqlcipher
- Solution of mysql8 forgetting password file in Windows Environment
- 简洁、快速、节约内存的Excel处理工具EasyExcel
猜你喜欢

"Matching" is true love, a new attitude for young people to make friends

【TS】1368- 秒懂 TypeScript 泛型工具类型!

Jsp webshell Free from killing - The Foundation of JSP

软件产品管理系统有哪些?12个最佳产品管理工具盘点

【快应用】text组件里的文字很多,旁边的div样式会被拉伸如何解决

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

Win11 arm系统配置.net core环境变量

4.随机变量

HDU1234 开门人和关门人(水题)

使用sqlcipher打开加密的sqlite方法
随机推荐
618再次霸榜的秘密何在?耐克最新财报给出答案
Convert yv12 to rgb565 image conversion, with YUV to RGB test
华为AppLinking中统一链接的创建和使用
Oracle 笔记
Is this code PHP MySQL redundant?
AppGallery Connect场景化开发实战—图片存储分享
Solution of mysql8 forgetting password file in Windows Environment
UWA报告使用小技巧,你get了吗?(第四弹)
In the face of uncertainty, the role of supply chain
MySQL lethal serial question 4 -- are you familiar with MySQL logs?
HDU1228 A + B(map映射)
Windows环境MySQL8忘记密码文件解决方案
集成学习概览
What are the popular frameworks for swoole in 2022?
UVM - configuration mechanism
AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘
[SUCTF2018]followme
Use WinDbg to statically analyze dump files (summary of practical experience)
axis设备的rtsp setup头中的url不能带参
js promise. all