搜索到叶子节点时往答案中添加。标准的DFS
class Solution {
public:
vector<string> res;
vector<string> binaryTreePaths(TreeNode* root) {
string s;
dfs(root,s);
return res;
}
void dfs(TreeNode* root, string s){
if(root==NULL){
return;
}
if(root->left==NULL&&root->right==NULL){
s+= to_string(root->val);
res.push_back(s);
return;
}
s+= to_string(root->val) + "->";
dfs(root->left,s);
dfs(root->right,s);
}
};