LeetCode *** 257. Binary Tree Paths
2016-04-10 14:50
357 查看
题目:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
分析:
用dfs即可。
代码:
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"]
分析:
用dfs即可。
代码:
/** * 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> res; stack<TreeNode*> tree; stack<string> tmpR; if(root){ tree.push(root); tmpR.push(to_string(root->val)); } while(!tree.empty()){ TreeNode *tmpNode=tree.top(); string tmp=tmpR.top(); tree.pop(); tmpR.pop(); if(tmpNode->left==NULL&&tmpNode->right==NULL) res.push_back(tmp); if(tmpNode->right){ tree.push(tmpNode->right); tmpR.push(tmp+"->"+to_string(tmpNode->right->val)); } if(tmpNode->left){ tree.push(tmpNode->left); tmpR.push(tmp+"->"+to_string(tmpNode->left->val)); } } return res; } };
相关文章推荐
- 邁向IT專家成功之路的三十則鐵律 鐵律十八:IT人求職之道-文化
- node入门(三)——gulp运用实例
- 生成动态代理并加入系统功能的设计模板
- Java并发编程:深入剖析ThreadLocal
- ajax全接触
- java 封装
- JAVA对象比较器Comparator
- 图的强连通性:Korasaju算法实现
- const与define之间的区别?
- 第七周项目二 利用友元类进行对时间与日期的修改
- [算法最优]设计一个有getMin功能的栈
- 15. 3Sum
- css选择器及其优先级
- LINQ的Except方法
- LINQ的Intersect方法
- 纹理特征提取——灰度共生矩阵
- 微积分计算图:反向传播算法
- cURL
- 表达式求值
- 【LeetCode】76. Minimum Window Substring