标签:+= push tree node ima code cto public 图片 void
递归先序遍历+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 };
标签:+= push tree node ima code cto public 图片 void
原文地址:https://www.cnblogs.com/joelwang/p/10453683.html