113. 路径总和 II
作者:互联网
✅做题思路or感想:
-
也是遍历一遍二叉树,判断路径总和和是否是叶子节点,要注意的是这里还需要加一个vector来记录路径
-
class Solution { public: vector<vector<int>>result; void dfs(TreeNode* cur, vector<int>vec, int sum) { //判断条件 if (sum == 0 && !cur->left && !cur->right) { result.push_back(vec); return; } else { if (cur->left) { //这里要有一个vector来记录路径 vec.push_back(cur->left->val); dfs(cur->left, vec, sum - cur->left->val); //回溯! vec.pop_back(); } if (cur->right) { vec.push_back(cur->right->val); dfs(cur->right, vec, sum - cur->right->val); vec.pop_back(); } } } vector<vector<int>> pathSum(TreeNode* root, int targetSum) { if (root == nullptr)return result; dfs(root, vector<int>{root->val}, targetSum - root->val); return result; } };
标签:right,cur,val,back,II,vector,vec,113,总和 来源: https://www.cnblogs.com/doomaa/p/16069627.html