原题地址

 

二叉树基本操作——遍历

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

 

代码:

 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 }

 

相关文章:

  • 2021-06-05
  • 2021-12-17
  • 2021-07-06
  • 2021-07-28
猜你喜欢
  • 2021-06-14
  • 2021-10-05
  • 2021-06-29
  • 2021-09-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-25
相关资源
相似解决方案