Binary Tree Paths
2015-08-16 14:14
260 查看
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> path; vector<string> finalResult; deepTravel(root,path,finalResult); return finalResult; } void deepTravel(TreeNode* root,vector<string>& tempPaths,vector<string>& finalResult) { //判断当前结点是否为空 if(root == NULL) return; //当前结点不为空就把当前结点的值转换为字符串。然后压入路径vector中 string temp; stringstream ss; ss<<root->val; ss>>temp; if(tempPaths.size()!=0)//如果前面已经有结点了,就添加箭头。 tempPaths.push_back("->"); tempPaths.push_back(temp); //如果当前结点没有左右子树,就将tempPath中的结点组合成一整个路径字符串。然后压入finalResult中 if(root->left == NULL && root->right==NULL) { string temp; for(vector<string>::iterator iter = tempPaths.begin(); iter!=tempPaths.end();iter++) { temp+=*iter; } finalResult.push_back(temp); return; } //如果当前结点有左右子树,就递归下去遍历 if(root->left != NULL) { deepTravel(root->left,tempPaths,finalResult); //先把左子树的结果弹出 tempPaths.pop_back(); tempPaths.pop_back(); } //如果当前结点有左右子树,就递归下去遍历 if(root->right != NULL) { deepTravel(root->right,tempPaths,finalResult); tempPaths.pop_back(); tempPaths.pop_back(); } } };
相关文章推荐
- POJ 3904 Sky Code (容斥+莫比乌斯反演)
- 图像处理算法回顾基本框架
- NUBT 1580 素数分解 母函数法解
- openstack中虚拟机怎么与物理机通信
- notify vs nofifyall
- SSH深度历险记(九) Struts2+DWZ+Uploadify多文件(文件和图片等。)上传
- oc对象方法
- svn网络服务器项目导入到Eclipse
- win 环境安装python 和 Py pip
- 8个DBA最常用的监控Oracle数据库的常用shell脚本
- 下拉刷新,在 ActionBar 上显示效果图
- Hadoop之MapReduce的两种任务模式
- oracle v$sqlarea 分析SQL语句使用资源情况 确认是否绑定变量
- LayoutInflater的原理分析【转载】
- POJ 3268 Silver Cow Party(dijkstra+矩阵转置)
- 1035. 插入与归并(25)
- 论函数的设计应如何才好,返回临时变量 | 返回引用 | 传递引用
- javascript函数
- yo angualr-fullstatck 项目打包部署
- git 两版本差异文件打包