当前位置:网站首页>二叉树专题--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传进来的是标量,不是地址
}
};
边栏推荐
猜你喜欢
随机推荐
【AGC】构建服务3-认证服务示例
What are the popular frameworks for swoole in 2022?
VSCode工具使用
UWA报告使用小技巧,你get了吗?(第四弹)
数据库字典Navicat自动生成版本
MySQL数据库远程访问权限设置
The URL in the RTSP setup header of the axis device cannot take a parameter
Overview of integrated learning
【AGC】如何解决事件分析数据本地和AGC面板中显示不一致的问题?
UVM learning - build a simple UVM verification platform
Mysql database remote access permission settings
2022爱分析· 国央企数字化厂商全景报告
【快应用】Win7系统使用华为IDE无法运行和调试项目
Hdu1236 ranking (structure Sorting)
UVM - usage of common TLM port
[visual studio] visual studio 2019 community version cmake development environment installation (download | install relevant components | create compilation execution project | error handling)
P1055 [NOIP2008 普及组] ISBN 号码
华为应用市场应用统计数据问题大揭秘
【ARK UI】HarmonyOS ETS的启动页的实现
Oracle notes









