题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
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>> ans; vector<int> path; int sum=0,target; void dfs(TreeNode* node){ sum += node->val; path.push_back(node->val); if(sum == target && node->left==NULL && node->right==NULL){ ans.push_back(path); sum -= node->val; path.pop_back(); return ; } if(node->left) dfs(node->left); if(node->right) dfs(node->right); sum -= node->val; path.pop_back(); } vector<vector<int>> FindPath(TreeNode* root,int expectNumber) { target = expectNumber; if(root == NULL) return ans; dfs(root); return ans; } };