C++
1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int val) { 8 * this->val = val; 9 * this->left = this->right = NULL; 10 * } 11 * } 12 */ 13 class Solution { 14 public: 15 /** 16 * @param root the root of the binary tree 17 * @return all root-to-leaf paths 18 */ 19 vector<string> binaryTreePaths(TreeNode* root) { 20 // Write your code here 21 vector<string> result; 22 if (root == NULL) { 23 return result; 24 } 25 string path=""; 26 binaryTreePathsCore(root, result, path); 27 return result; 28 } 29 void binaryTreePathsCore(TreeNode* root, vector<string> &result, string path) { 30 if (root == NULL) { 31 return; 32 } 33 int i = root->val; 34 char a[5]; 35 // itoa(i, a, 10); 36 sprintf(a, "%d", i); 37 if ("" == path) { 38 path = a; 39 } else { 40 path = path + "->" + a; 41 } 42 if (root->left == NULL && root->right == NULL) { 43 result.push_back(path); 44 return; 45 } 46 if (root->left != NULL) { 47 binaryTreePathsCore(root->left, result, path); 48 } 49 if (root->right != NULL) { 50 binaryTreePathsCore(root->right, result, path); 51 } 52 53 54 } 55 };