Binary Tree Paths
2024-08-24 18:23:20
Description:
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"]
Code:
void allPath(TreeNode*root, vector<string>&result, vector<int>&path)
{
if (root==NULL)
return ;
path.push_back(root->val);
if (root->left==NULL && root->right==NULL)
{
//注意这里要用ostringstream将字符串写到流中去,然后用str()函数返回字符串
ostringstream sstr;
for (int i = ; i < path.size()-; ++i)
sstr << path[i]<<"->";
sstr<<path[path.size()-];
result.push_back(sstr.str());
}
else
{
if (root->left)
allPath(root->left, result, path);
if (root->right)
allPath(root->right, result, path);
}
path.pop_back();
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>result;
vector<int>path;
allPath(root, result,path);
return result;
}
最新文章
- python学习笔记- 多线程(1)
- there&#39;s no qt version assigned to this project for platform
- Tomcat基本使用
- C#------EntityFramework实体加载数据库SQLServer(MySQL)
- oracle给字段添加描述
- 菜鸟学习Hibernate——简单的一个例子
- Android 官方文档:(二)应用清单 —— 2.2 &;lt;action&;gt;标签
- [项目构建 十三]babasport Nginx负载均衡的详细配置及使用案例详解.
- KVM硬件辅助虚拟化之 EPT(Extended Page Table)
- JS判断请求来自Android手机还是iPhone手机,根据不同的手机跳转到不同的链接。
- WPF笔记(1.6 数据绑定)——Hello,WPF!
- ***1133. Fibonacci Sequence(斐波那契数列,二分,数论)
- SDOI2017 Round2 详细题解
- c# 观察者模式 匿名方法与Lambda
- [HNOI2015]菜肴制作(拓扑排序)
- 读《31天学会CRM项目开发》记录1 - 认识软件开发
- python学习之----收集整个网站
- ConcurrentHashMap源码解析(1)
- MySQL笔记(三)由txt文件导入数据
- Oracle递归查询(start with)