当前位置:网站首页>二叉树专题--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传进来的是标量,不是地址
}
};
边栏推荐
- JSP webshell free -- the basis of JSP
- SPSS做Shapiro-Wilk正态分析
- LabVIEW为什么浮点数会丢失精度
- 13. Semaphore critical zone protection
- PCL之K-d树与八叉树
- Learn open62541 -- [66] UA_ Generation method of string
- 集成学习概览
- MySQL数据库远程访问权限设置
- Dialogue Wu Gang: why do I believe in the rise of "big country brands"?
- UVM - configuration mechanism
猜你喜欢

HDU1236 排名(结构体排序)

SUS系统可用性量表

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

618再次霸榜的秘密何在?耐克最新财报给出答案

2022-06-17

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

12.进程同步与信号量

Internet News: Tencent conference application market was officially launched; Soul went to Hong Kong to submit the listing application

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

Retrofit's callback hell is really vulnerable in kotlin synergy mode!
随机推荐
《实习报告》Skywalking分布式链路追踪?
华为快应用中如何实现同时传递事件对象和自定义参数
js promise. all
Windows环境MySQL8忘记密码文件解决方案
Nodejs+express+mysql simple blog building
转换YV12到RGB565图像转换,附YUV转RGB测试
Introduction to MySQL 8 DBA foundation tutorial
【快应用】Win7系统使用华为IDE无法运行和调试项目
LabVIEW为什么浮点数会丢失精度
JSP webshell免殺——JSP的基礎
js数组常用方法
MySQL environment configuration
Shell programming 01_ Shell foundation
【ARK UI】HarmonyOS ETS的启动页的实现
学习open62541 --- [66] UA_String的生成方法
13.信号量临界区保护
session-cookie与token
Pywin32 opens the specified window
数据库字典Navicat自动生成版本
UWA report uses tips. Did you get it? (the fourth bullet)