Binary Tree Paths
2015-08-31 21:40
253 查看
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> binaryTreePaths(TreeNode* root) {
vector<string> result;
if(root)
paths(root, result, to_string(root->val));
return result;
}
void paths(TreeNode* node, vector<string> &result, string str) {
if(!node->left && !node->right) {
result.push_back(str);
return;
}
if(node->left) {
paths(node->left, result, str + "->" + to_string(node->left->val));
}
if(node->right) {
paths(node->right, result, str + "->" + to_string(node->right->val));
}
}
};
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;
if(root)
paths(root, result, to_string(root->val));
return result;
}
void paths(TreeNode* node, vector<string> &result, string str) {
if(!node->left && !node->right) {
result.push_back(str);
return;
}
if(node->left) {
paths(node->left, result, str + "->" + to_string(node->left->val));
}
if(node->right) {
paths(node->right, result, str + "->" + to_string(node->right->val));
}
}
};
相关文章推荐
- 免费自学Cocos2d-x3.0final2014原创视频教程(56集)(适用于Cocos2d-x3.1 Cocos2d-x3.2版本全)
- 台湾国立大学机器学习基石.听课笔记(第十六讲一):Three Learning Principle
- SQL Server2012 元数据管理器中存在错误
- Android中如何获取系统应用程序列表与AndroidManifest.xml信息
- leetcode 238: Product of Array Except Self
- android开发步步为营之72:右滑关闭Activity
- 通过GDB重新获得进程的输出
- 第十章 方差分析
- UIday0603:UIImageView的属性和用法 Tom猫举例
- EasyUI——常见用法总结
- 【工具系列一】——Tomcat的基本配置
- 组态软件在电动汽车充电站监控系统中的应用
- eightQueen1.0
- 页面跳转之Forward和Redirect
- 浅谈iOS中MVVM的架构设计与团队协作
- 总结_高效能人士的七个习惯
- Java导论(一)
- 斯坦福大学iOS应用开发教程学习笔记(第三课) Objective-C
- win7(windows 7)系统下安装SQL2005(SQL Server 2005)图文教程
- java环境变量