path-sum-ii leetcode C++
2024-09-07 18:45:08
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] ]
C++
/**
* 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>> dp;
vector<int> path;
getPath(root,sum,dp,path);
return dp;
}
void getPath(TreeNode *root, int sum,vector<vector<int>>& dp,vector<int> path){
if(NULL == root) return;
path.push_back(root->val);
if(NULL == root->left && NULL == root->right && root->val == sum )
dp.push_back(path);
getPath(root->left,sum - root->val,dp,path);
getPath(root->right,sum - root->val,dp,path);
}
};
最新文章
- Boostrap入门(一)
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(39)-在线人数统计探讨
- Code Complete 笔记—— 第二章 用隐喻来更充分理解软件开发
- 项目集成ReactiveCocoa遇到的坑及解决办法
- webapp中的meta
- zpf 路由功能
- winform小程序---猜拳小游戏
- OD调试篇9
- Git Shell 安装版本
- [HDOJ5943]Kingdom of Obsession(最大匹配,思路)
- Android Activity的切换动画
- jquery文本折叠
- .Echo 命令中经常提到回显,是什么意思?
- VS SQL 出现%CommonDir%dte80a.olb 该解决方案
- SQL的自增列重置的方法
- ●CodeChef Sereja and Game
- 再探go modules:使用与细节
- 测序数据质控-FastQC
- 《python语言程序设计》_第二章笔记
- java常见错误总结