【树】【回溯】 leetcode_257 _ 二叉树的所有路径
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
re(root, path, result);
return result;
}
void re(TreeNode *cur ,vector<int> &path, vector<string> &result){
path.push_back(cur->val);
if (cur->left==nullptr && cur ->right == nullptr){
string p_m;
for (int i = 0; i < path.size()-1; i++){
p_m += to_string(path[i]);
p_m +="->";
}
p_m+=to_string(*path.rbegin());
result.push_back(p_m);
return;
}
if(cur->left != nullptr){
re(cur->left, path,result);
path.pop_back();
}
if(cur->right != nullptr){
re(cur->right, path,result);
path.pop_back();
}
}
};