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] ]
分析:
这题并不难。其实就是深搜。
就是可能一开始,觉得函数递归的时候,要传哪些参数下去?要返回那些值??
当有多个返回值的时候怎么办??
Trick: C++ 中可以采用引用,来返回值的功能。
1. 返回值: 多条 paths, 可以将 vector<vector<int> >& result 作为形参; 这样其实 所有的递归函数都共享了这个 vector; 当找到路径时,push_back即可。
2. 需要往下传的参数: 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> > result; vector<int> path; MyPathSum(root, sum, path, result); return result; } private: void MyPathSum(TreeNode *root, int sum, vector<int> &path, vector<vector<int> > &result) { if(root == NULL) return; path.push_back(root->val); if(root->left == NULL && root->right == NULL){ if(sum == root->val){ result.push_back(path); } } if(root->left){ MyPathSum(root->left, sum - root->val, path, result); } if(root->right){ MyPathSum(root->right, sum - root->val, path, result); } path.pop_back(); } };
原文:http://blog.csdn.net/shoulinjun/article/details/19841151