[leetcode][tree] Binary Tree Paths
2015-08-16 13:34
411 查看
题目:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
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"]
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <stdlib.h> class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if(root == NULL) return res; string onePath; binaryTreePathsCore(root, onePath, res); return res; } private: char *itoa(int x, char *str){ if(x == 0){ str[0] = '0'; str[1] = '\0'; return str; } int i = 0; if(x < 0){ x = -x; str[i++] = '-'; } int start = i; while(x > 0){ str[i++] = x%10+'0'; x /= 10; } str[i] = '\0'; reverse(str+start, str+i); return str; } void binaryTreePathsCore(TreeNode *root, string onePath, vector<string> &res){ if(root == NULL) return; char str[12]; itoa(root->val, str); onePath += str; if(root->left == NULL && root->right == NULL){ res.push_back(onePath); return; } onePath += "->"; if(root->left != NULL) binaryTreePathsCore(root->left, onePath, res); if(root->right != NULL) binaryTreePathsCore(root->right, onePath, res); } };
相关文章推荐
- 【effective c++读书笔记】【第7章】模板和泛型编程(2)
- 在ASP.NET MVC中使用 Bootstrap table插件
- 【effective c++读书笔记】【第7章】模板和泛型编程(2)
- LSC 最长公共序列
- php和apache安装memcache的过程
- Android Material Design带UI变化
- Android中自定义RatingBar
- Spring如何装配各种集合类属性
- UVA 10746 Crime Wave - The Sequel【最小费用最大流】
- hdu5393 Falsyta in Tina Town
- Git 学习笔记
- SpringMVC的页面跳转
- poj 2570 floyd+二进制
- python-requests快速上手
- redis
- 点击一个按钮使其下面的主题背景变色
- 文本对齐方式
- 当你在浏览器地址栏输入一个URL后回车,将会发生的事情?
- O(n)预处理C(n,m)
- webview 中使用css适配简单的页面