leetcode 113 path Sum II 路径和

Posted Joel_Wang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 113 path Sum II 路径和相关的知识,希望对你有一定的参考价值。

 

递归先序遍历+vector<int>容器记录路径

 

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> pathSum(TreeNode* root, int sum) {
13         vector<int> out;
14         vector<vector<int>> res;
15         dfs(root,sum,0,out,res);
16         return res;
17     }
18     //还是递归先序遍历+vector<int>容器记录路径
19     void dfs(TreeNode* node,int sum,int curSum,vector<int> &out,vector<vector<int>> &res){
20         if(!node) return;
21         curSum+=node->val;
22         out.push_back(node->val);
23         if(node->left==NULL&&node->right==NULL&&curSum==sum) res.push_back(out);
24         dfs(node->left,sum,curSum,out,res);
25         dfs(node->right,sum,curSum,out,res);
26         out.pop_back();
27     }
28 };

 

以上是关于leetcode 113 path Sum II 路径和的主要内容,如果未能解决你的问题,请参考以下文章

leetcode [113]Path Sum II

[LeetCode] 113. Path Sum II 路径和 II

LeetCode 113. Path Sum II

Leetcode 113: Path Sum II

LeetCode 113:Path Sum II

LeetCode113 Path Sum II