[LeetCode] Path Sum II
2015-06-18 15:06
519 查看
Path Sum II
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 and
sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
解题思路:
深度优先递归搜索。注意节点的值可能是负数。
/**
* 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:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> result;
vector<int> resultItem;
helper(result, resultItem, root, sum);
return result;
}
void helper(vector<vector<int>>& result, vector<int> resultItem, TreeNode* root, int leftSum){
if(root==NULL){
return;
}
if(root->left==NULL && root->right==NULL){ //root为叶子节点
if(leftSum==root->val){
resultItem.push_back(root->val);
result.push_back(resultItem);
}
}else{
resultItem.push_back(root->val);
leftSum = leftSum - root->val;
if(root->left!=NULL){
helper(result, resultItem, root->left, leftSum);
}
if(root->right!=NULL){
helper(result, resultItem, root->right, leftSum);
}
}
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++中拷贝构造函数的应用详解
- C++中引用(&)的用法与应用实例分析
- C++使用CriticalSection实现线程同步实例
- C++智能指针实例详解
- 解析C++ 浮点数的格式化输出