刚又刷了一道题,虽然本题编程思路也有些绕,但有了前面题目的经验,其实也还好啦。下面就和大家分享一下经验吧!
题目如下:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
题意分析:
给定一个二叉树和一个sum值,请返回所有满足从根节点到叶子节点值之和为sum的路径。
方法一(递归法)
在“https://blog.csdn.net/Vensmallzeng/article/details/95306500”方法一的基础上稍作修改,最后在返回满足条件的路径时还需要将路径节点值通过reverse函数进行反转,因为在递归调用时是反着存入路径节点值的。
解题代码如下:
class Solution{
public:
vector<vector<int>> pathSum(TreeNode* root, int sum){
vector<vector<int>> temp, res;
temp = pathSum(root);
for (int i = 0; i < temp.size(); i++) {
int total = 0;
for (int j = 0; j < temp[i].size(); j++) {
total += temp[i][j];
}
if(total == sum) {reverse(temp[i].begin(),temp[i].end()); res.push_back(temp[i]);}
}
return res;
}
vector<vector<int>> pathSum(TreeNode* root){
vector<vector<int>> res;
if(root == NULL) return res;
if(root->left == NULL && root->right == NULL) {res.push_back({root->val}); return res;}
vector<vector<int>> leftpath = pathSum(root->left);
for (int i = 0; i < leftpath.size(); i++) {leftpath[i].push_back(root->val); res.push_back(leftpath[i]);}
vector<vector<int>> rightpath = pathSum(root->right);
for (int i = 0; i < rightpath.size(); i++) {rightpath[i].push_back(root->val); res.push_back(rightpath[i]);}
return res;
}
};
提交后的结果如下:
方法二(优化方法一)
本题采用深度优先遍历DFS解决,每当DFS搜索到一个叶子节点时(相当于找到一条路径),都将该路径保存到一维vector中,如果该路径满足从根节点到叶子节点值之和为sum,则保存该路径到二维vector中,否则需要在返回上一个结点的之前需要把当前节点从一维vector中移除,最后返回二维vector即为所求结果。
解题代码如下:
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int>> res;
vector<int> temp;
pathSum_son(root, sum, temp, res);
return res;
}
void pathSum_son(TreeNode* node, int sum, vector<int>& temp, vector<vector<int>>& res) {
if (!node) return;
temp.push_back(node->val);
if (sum == node->val && !node->left && !node->right) {
res.push_back(temp);
}
pathSum_son(node->left, sum - node->val, temp, res);
pathSum_son(node->right, sum - node->val, temp, res);
temp.pop_back();
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。