LintCode: Binary Tree Paths
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 };
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。