当前位置:网站首页>二叉树专题--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传进来的是标量,不是地址
}
};
边栏推荐
猜你喜欢

(5) Gear control setting of APA scene construction

AI技术产业热点分析

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

Retrofit's callback hell is really vulnerable in kotlin synergy mode!

JSP webshell free -- the basis of JSP

如何使用IDE自动签名调试鸿蒙应用

Kustomize使用手册

Mysql database remote access permission settings

Shutter - canvas custom graph
![[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)
随机推荐
2022爱分析· 国央企数字化厂商全景报告
js数组常用方法
Shutter - canvas custom graph
Read H264 parameters from mediarecord recording
Leetcode+ 76 - 80 storm search topic
How to get the password of cpolar?
14.信号量的代码实现
软件产品管理系统有哪些?12个最佳产品管理工具盘点
Mysql database remote access permission settings
LeetCode+ 76 - 80 暴搜专题
PCL extracts a subset from a point cloud
flume 190 INSTALL
大华设备播放过程中设置播放速度
JSP webshell免杀——JSP的基础
[SUCTF2018]followme
AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘
"Matching" is true love, a new attitude for young people to make friends
Ks009 implement pet management system based on SSH
JSP webshell free -- the basis of JSP
axis设备的rtsp setup头中的url不能带参