递归法,比较慢,但是可以解决问题。
一个点:
给定val,求对应的string,如果是非负整数,可以用'0'+val;
如果有可能是负数或者其他数,to_string(val);
拓展:
stoi(s,p,q)把s从第p位转换为q进制的数
stod, stof;
此外c含有atoi等
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> answer;
if(root == NULL) return answer;
if(root->left == NULL && root->right == NULL){
string s;
s += to_string(root->val);
answer.push_back(s);
return answer;
}else{
vector<string> v1 = binaryTreePaths(root->left);
vector<string> v2 = binaryTreePaths(root->right);
v1.insert(v1.end(), v2.begin(), v2.end());
string current = to_string(root->val);
string temp = "->";
for(auto& s : v1){
s = current + temp + s;
}
return v1;
}
}
};