LeetCode 257. Binary Tree Paths
2016-07-25 16:15
295 查看
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
/**
* 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> v;
void path(TreeNode* root, string s){
if(!root->left && !root->right){
ostringstream o;
o << root->val;
if(s != "") s = s + "->" + o.str();
else s = o.str();
v.push_back(s);
}
if(root->left){
ostringstream o;
o << root->val;
string tmp = s;
if(tmp != "") tmp = tmp + "->" + o.str();
else tmp = o.str();
path(root->left, tmp);
}
if(root->right){
ostringstream o;
o << root->val;
string tmp = s;
if(tmp != "") tmp = tmp + "->" + o.str();
else tmp = o.str();
path(root->right, tmp);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if(root == NULL) return v;
path(root, "");
return v;
}
};
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> v;
void path(TreeNode* root, string s){
if(!root->left && !root->right){
ostringstream o;
o << root->val;
if(s != "") s = s + "->" + o.str();
else s = o.str();
v.push_back(s);
}
if(root->left){
ostringstream o;
o << root->val;
string tmp = s;
if(tmp != "") tmp = tmp + "->" + o.str();
else tmp = o.str();
path(root->left, tmp);
}
if(root->right){
ostringstream o;
o << root->val;
string tmp = s;
if(tmp != "") tmp = tmp + "->" + o.str();
else tmp = o.str();
path(root->right, tmp);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if(root == NULL) return v;
path(root, "");
return v;
}
};
相关文章推荐
- 西宇鼠标点击大师 V3.2 官方正式版
- 快速搭建hadoop+hbase分布式集群
- Linux 关机/重启/注销命令(7个)
- 设计模式-职责链模式
- Redis 高级: Redis 集群cluster
- Composer切换镜像
- 日常一些小问题与解决方案总结
- 一个字符串有多个img如何取出来 ?
- GEN_CLUST_INDEX锁
- HDU 5750 BestCoder Round #84 Dertouzos (素数筛选)
- Redis 高级: Redis 双击热备之 keepalived
- java 文件操作
- 资料收藏夹
- 刮刮奖
- IIS6配置Asp.net MVC运行环境
- 阿里云资深DBA专家罗龙九:云数据库十大经典案例分析【转载】
- MTK mmi应用程序本质
- UML类图实例讲解
- poj 2484A Funny Game(博弈论)
- 旋转卡壳