Binary Tree Paths
2016-01-30 20:31
309 查看
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
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) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; vector<int> buf; visit(root, buf, result); return result; } private: void visit(TreeNode *root, vector<int> &buf, vector<string> &result) { if (root == NULL) { return; } buf.push_back(root->val); if (root->left == NULL && root->right == NULL) { string cur; char temp[10]; sprintf(temp, "%d", buf[0]); cur += temp; for (int i = 1; i < buf.size(); i++) { sprintf(temp, "%d", buf[i]); cur += "->"; cur += temp; } result.push_back(cur); } else { visit(root->left, buf, result); visit(root->right, buf, result); } buf.pop_back(); } };
相关文章推荐
- Android 基础—— 对Context的理解与使用技巧
- 你为什么要来北京?
- NYOJ-开灯问题
- python中global 和 nonlocal 的作用域
- 软件开发管理:系统设计和技术原型
- codevs1008
- 父子控制器
- RecyclerView简易底部上拉刷新
- 学习CSS了解单位em和px的区别
- 日期4
- Class org.apache.struts2.json.JSONWriter can not access a member of class
- 【BZOJ1196】公路修建问题,二分+最小生成树
- Java初学之集合(二)
- php正则匹配文章中的远程图片地址并下载图片到本地
- MATLAB随机数:重启后结果一样解决方法
- Instruments Tutorial with Swift: Getting Started
- C++数组作为函数参数的几个问题(转)
- Paxos Made Simple【翻译】
- zoj 2966 Build The Electric System【最小生成树 Kruskal && prim】
- 修改mysql 表引擎类型错误