使用dfs
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(root) dfs(root,"",res);
return res;
}
void dfs(TreeNode* root,string str1,vector<string> &res){
str1+=to_string(root->val);
if(!root->left&&!root->right) res.push_back(str1);
else{
if(root->left) dfs(root->left,str1+"->",res);
if(root->right) dfs(root->right,str1+"->",res);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return {};
if(!root->left&&!root->right) return{to_string(root->val)};
vector<string>left=binaryTreePaths(root->left);
vector<string>right=binaryTreePaths(root->right);
left.insert(left.end(),right.begin(),right.end());
for(auto &a:left){
a=to_string(root->val)+"->"+a;
}
return left;
}