给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
返回:
[ [5,4,11,2], [5,8,4,5] ]
解题思路:
解题思路与Leetcode:112.路径总和,一致,只不过要存储已访问的路径,注意事项:最好将路径数组,当前的和,设置为类的成员,已避免在DFS函数中重复创建。一般而言,创建一个变量、数组要比修改它们更加耗时。
https://blog.csdn.net/qq_23523409/article/details/83750939
#define hasLChild(x) (!(x->left==NULL)) #define hasRChild(x) (!(x->right==NULL)) #define hasNoChild(x) (!hasLChild(x)&&!hasRChild(x)) class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { if (root == NULL) return{}; _sum = sum; DFS(root); return res; } void DFS(TreeNode* root) { if (hasNoChild(root)) { if (root->val == _sum) { road.push_back(root->val); res.push_back(road); } return; } road.push_back(root->val); int size = road.size(); _sum -= root->val; int sgn = _sum; if (hasLChild(root)) DFS(root->left); road.erase(road.begin() + size, road.end()); _sum = sgn; if (hasRChild(root)) DFS(root->right); } private: vector<vector<int>> res; int _sum; vector<int> road; }; |