[Leetcode] Path Sum II路径和
2024-08-31 12:35:09
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
] 题意:给定一数,在树中找出所有路径和等于该数的情况。
方法一:
使用vector向量实现stack的功能,以方便输出指定路径。思想和代码和Path sum大致相同。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum)
{
vector<vector<int>> res;
vector<TreeNode *> vec;
TreeNode *pre=NULL;
TreeNode *cur=root;
int temVal=; while(cur|| !vec.empty())
{
while(cur)
{
vec.push_back(cur);
temVal+=cur->val;
cur=cur->left;
}
cur=vec.back();
if(cur->left==NULL&&cur->right==NULL&&temVal==sum)
{ //和Path sum最大的区别
vector<int> temp;
for(int i=;i<vec.size();++i)
temp.push_back(vec[i]->val);
res.push_back(temp);
}
if(cur->right&&cur->right !=pre)
cur=cur->right;
else
{
vec.pop_back();
temVal-=cur->val;
pre=cur;
cur=NULL;
} }
return res;
}
};
方法二:递归法
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum)
{
vector<vector<int>> res;
vector<int> path;
findPaths(root,sum,res,path);
return res;
}
void findPaths(TreeNode *root,int sum,vector<vector<int>> &res,vector<int> &path)
{
if(root==NULL) return;
path.push_back(root->val);
if(root->left==NULL&&root->right==NULL&&sum==root->val)
res.push_back(path); findPaths(root->left,sum-root->val,res,path);
findPaths(root->right,sum-root->val,res,path);
path.pop_back();
}
};
最新文章
- 配置 nginx server 出现nginx: [emerg] ";root"; directive is duplicate in /etc/nginx/server/blogs.conf:7
- poj 3159 Candies 差分约束
- 批量修改照片名称的shell脚本
- C#_字符串的操作
- 例题6-7 Trees on the level ,Uva122
- Nginx下载服务生产服务器调优
- initMethod 和 afterPropertiesSet 以及 AwareMethod方法的执行时机
- 帝国cms栏目死变量
- MySQL filesort优化案例一则
- 根据NSString字符串长度自动改变UILabel的frame
- Ubuntu14.04安装有道词典
- (笔记):组合and继承之访问限制(一)
- Django学习目录
- java中的HMAC-SHA1加密
- 虚函数 error LNK2001: 无法解析的外部符号 ";public: virtual void __cdecl
- <;ROS>; NodeHandle句柄
- JWT 认证 以及Django 中的应用
- 华硕R系列的解剖图
- Microsoft JET Database Engine 错误 &#39;80004005&#39; 未指定错误
- ElasticSearch入门 第四篇:使用C#添加和更新文档