使用vector<string>来存储数据,并且使用递归
里面函数的应用:
to_string 函数:将数字常量转换为字符串,返回值为转换完毕的字符串
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void solve(TreeNode* root,string path,vector<string>& v){
if(root!=NULL){
path+=to_string(root->val);
if(root->left==NULL&&root->right==NULL){// 当前节点是叶子节点
v.emplace_back(path); // 把路径加入到答案中
}
else{
path+="->"; // 当前节点不是叶子节点,继续递归遍历
solve(root->left,path,v);
solve(root->right,path,v);
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> v;
solve(root,"",v);
return v;
}
};