Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
For example:sum = 22
,
5
/ 4 8
/ / 11 13 4
/ \ / 7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
#include <iostream> #include <vector> using std::vector; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { private: void pathSum(TreeNode* root, int sum, vector<vector<int> > &Result, vector<int> &TmpResult) { if (!root) { return; } if (!root->left && !root->right && root->val == sum) { TmpResult.push_back(sum); Result.push_back(TmpResult); // pop the leaf node TmpResult.pop_back(); return; } int SumChild = sum - root->val; TmpResult.push_back(root->val); pathSum(root->left, SumChild, Result, TmpResult); pathSum(root->right, SumChild, Result, TmpResult); // pop the current node TmpResult.pop_back(); } public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int> > Result; vector<int> TmpResult; pathSum(root, sum, Result, TmpResult); return Result; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/sheng_ai/article/details/46695379