Leetcode#113 Path Sum II

时间:2015-01-30 14:34:35   收藏:0   阅读:226

原题地址

 

二叉树基本操作——遍历

题目没说数字都是正数,所以没法剪枝,只能全部遍历一遍。

 

代码:

 1 vector<vector<int> > res;
 2     
 3 void traverse(TreeNode *root, vector<int> ans, int sum) {
 4   if (!root)
 5     return;
 6             
 7   ans.push_back(root->val);
 8   if (!root->left && !root->right) {
 9     if (sum == root->val)
10       res.push_back(ans);
11     return;
12   }
13   traverse(root->left, ans, sum - root->val);
14   traverse(root->right, ans, sum - root->val);
15 }
16     
17 vector<vector<int> > pathSum(TreeNode *root, int sum) {
18   traverse(root, vector<int>(), sum);
19   return res;
20 }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!