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"]
Analyse: Recursion.
Runtime: 4ms.
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<string> binaryTreePaths(TreeNode* root) { 13 vector<string> result; 14 if(!root) return result; 15 16 dfs(root, result, ""); 17 return result; 18 } 19 void dfs(TreeNode* root, vector<string>& result, string temp){ 20 if(!root) return; 21 22 temp = temp + std::to_string(root->val); 23 if(root->left) dfs(root->left, result, temp + "->"); 24 if(root->right) dfs(root->right, result, temp + "->"); 25 if(!root->left && !root->right) result.push_back(temp); 26 } 27 /*string i2a(int val){ 28 if(val == 0) return "0"; 29 30 string result; 31 if(val < 0){ 32 result += "-"; 33 val = -val; 34 } 35 while(val){ 36 result += val % 10 + '0'; 37 val /= 10; 38 } 39 int i = 0; 40 if(result[0] = '-') i = 1; 41 for(int j = result.length() - 1; i <= j; i++, j--){ 42 swap(result[i], result[j]); 43 } 44 return result; 45 }*/ 46 };