Leetcode#113 Path Sum II

原题地址

 

二叉树基本操作——遍历

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

 

代码:

 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 }

 

你可能感兴趣的:(LeetCode)