Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

 

   1
 /   \
2     3
 \
  5

 

All root-to-leaf paths are:

["1->2->5", "1->3"]


 1 class Solution {
 2 public:
 3     vector<vector<int>> res;
 4     void backtrack(TreeNode* root, vector<int>& path) {  
 5         if (root == nullptr) return;
 6         if(root->left == nullptr && root->right == nullptr) {
 7             path.push_back(root->val);
 8             res.push_back(path);
 9             path.pop_back();
10             return;
11         }
12         path.push_back(root->val);
13         backtrack(root->left,path);
14         backtrack(root->right,path);
15         path.pop_back();
16     }
17     vector<string> binaryTreePaths(TreeNode* root) {
18         vector<string> final_res;
19         vector<int> path;
20         backtrack(root,path);
21         for(auto vec: res){
22             string path_str = "";
23             for(auto int i = 0;i < vec.size(); ++i){
24                 path_str.append(to_string(vec[i]));
25                 if (i != vec.size() - 1) path_str.append("->");
26             }
27             final_res.emplace_back(path_str);
28         }
29         return final_res;
30     }
31 };

 

 

相关文章: