LeetCode || Path Sum II
2015-07-29 20:25
387 查看
Path Sum II
耗时:16ms
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
return
耗时:16ms
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: int curr = 0; bool flag = false; vector<vector<int>> v; vector<int> cv; void dfs(TreeNode* root, int sum) { if(curr == sum && root->left == NULL && root->right == NULL) { flag = true; v.push_back(cv); return; } if(root->left!=NULL) { cv.push_back(root->left->val); curr+=root->left->val; dfs(root->left, sum); curr-=root->left->val; cv.pop_back(); } if(root->right!=NULL) { cv.push_back(root->right->val); curr+=root->right->val; dfs(root->right, sum); curr-=root->right->val; cv.pop_back(); } } vector<vector<int>> pathSum(TreeNode* root, int sum) { if(root == NULL) return v; curr+=root->val; cv.push_back(root->val); dfs(root, sum); return v; } };
相关文章推荐
- 2015 Multi-University Training Contest 3 1002 RGCDQ
- 如何用 Parse 和 Swift 搭建一个像 Instagram 那样的应用?
- Two Sum
- python学习——Numpy(1)
- UIView
- zoj 3726 水题+二分
- poj 3268 Silver Cow Party(dijkstra||SPFA)(中等)
- 游戏时间逻辑计算问题
- 1019. General Palindromic Number (20)
- Two Sum
- Children of the Candy Corn
- 黑马程序员———TreeSet两种排序方式
- VS2008 C# 调用C++DLL
- OC10-Block
- ie下select默认样式修改
- [bug]Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding
- 如何使用Maven创建web工程(详细步骤)
- how to combine jpg + separate alpha in png?
- ThreadingTest(线程测试)领先的白框进入这个行业
- 金融脱媒砸进?