Leetcode257
1.问题描述
2.解决方案
解法一:递归
总结
本道题一看收集节点信息这种就想到要使用递归回溯,那么直接上回溯模板
1.递归出口,如果遇到空结点直接return回溯就好,如果遇到叶子节点那么就需要收集一下结果
if(root== nullptr){
//ans.push_back(string(path.begin(),path.end()-2));
return;
}
if(root->left== nullptr&&root->right== nullptr){
//path.push_back(char(root->val+48));
path+= to_string(root->val);
ans.push_back(path);
return;
}
2.由于需要回溯所以把记录路径的path设置为了函数参数,这样就起到了回溯的效果,递归完左子树,到递归右子树的时候path还只是root没有变化,这就代表发生了回溯,尽管不是显式的
backtracking(root->left,path);
backtracking(root->right,path);
3.就是收集路径过程使用的数据结构这个也得好好考虑,首先path使用string类型,收集的时候直接用+来合并字符串没毛病,然后就是把数组转化成char或者string合并的时候,一开始使用了path.push_back(char(root->val+48)),发现如果是负数就不对了,这下清楚了以后直接to_string()!
代码:
class Solution {
public:
vector<string> ans;
//string path;
void backtracking(TreeNode* root,string path){
if(root== nullptr){
//ans.push_back(string(path.begin(),path.end()-2));
return;
}
if(root->left== nullptr&&root->right== nullptr){
//path.push_back(char(root->val+48));
path+= to_string(root->val);
ans.push_back(path);
return;
}
//path.push_back(char(root->val+48));
//path.push_back('-');
//path.push_back('>');
path+= to_string(root->val);
path+= "->";
backtracking(root->left,path);
backtracking(root->right,path);
}
vector<string> binaryTreePaths(TreeNode* root) {
string path;
backtracking(root,path);
return ans;
}
};
解法二:迭代
就是利用统一迭代前序遍历模拟遍历路径的过程
又涉及到那个统一迭代法,这个我还没看