题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: vector<vector<int>> all(TreeNode*root){ vector<vector<int>> ans; if(root==nullptr){ return ans; } if(root->left==nullptr&&root->right==nullptr){ vector<int> t(1,root->val); ans.push_back(t); return ans; } vector<vector<int>> vecl=all(root->left); for(int i=0;i<vecl.size();i++){ vecl[i].push_back(root->val); ans.push_back(vecl[i]); } vector<vector<int>> vecr=all(root->right); for(int i=0;i<vecr.size();i++){ vecr[i].push_back(root->val); ans.push_back(vecr[i]); } return ans; } vector<vector<int>> FindPath(TreeNode* root,int expectNumber) { vector<vector<int>> a=all(root); vector<vector<int>> ans; for(int i=0;i<a.size();i++){ int t=0; for(int j=0;j<a[i].size();j++){ t+=a[i][j]; } if(t==expectNumber){ vector<int> t; for(int j=a[i].size()-1;j>=0;j--){ t.push_back(a[i][j]); } ans.push_back(t); } } return ans; } };