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 };
![字节跳动内推](https://img2020.cnblogs.com/blog/323808/202004/323808-20200415172728571-1992447742.jpg)
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步