思路:用一个path变量保存一条路径,判断标准是否是叶子节点。注意一点vector类似于int,如果想要按地址传递参数的话,需要加&变成引用,将int转换为string用to_string()函数。
class Solution {
public:
void allpath(TreeNode *root,string path,vector<string> &paths){
if(root!=NULL){
path+=to_string(root->val);
if(root->left==NULL&&root->right==NULL){
paths.push_back(path);
}
else{
path+="->";
allpath(root->left,path,paths);
allpath(root->right,path,paths);
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;
if(root!=NULL){
allpath(root,"",paths);
}
return paths;
}
};