leetcode Binary Tree Paths
2015-12-11 21:01
197 查看
题目:
分析:让你对一棵树进行遍历,找出所有从跟节点到到叶子节点的路径,每条路径作为一个string保存到vector < string> 里面。只是对树的递归遍历,但是令人吃惊的是这道题在leetcode上只有 24%的通过率。
代码:
[code]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"]
分析:让你对一棵树进行遍历,找出所有从跟节点到到叶子节点的路径,每条路径作为一个string保存到vector < string> 里面。只是对树的递归遍历,但是令人吃惊的是这道题在leetcode上只有 24%的通过率。
代码:
[code]/** * 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> res ; void getPath(TreeNode* root,string s) { if(root->right == NULL && root->left == NULL) res.push_back(s); if(root->left!=NULL) { string s1 ; s1 = s + "->" + int2string(root->left->val); cout << s1 << endl; getPath(root->left,s1); } if(root->right!=NULL) { string s1 ; s1 = s + "->" + int2string(root->right->val); cout << s1 << endl; getPath(root->right,s1); } } string int2string(int Number) { string Result; stringstream convert; convert << Number; Result = convert.str(); return Result; } vector<string> binaryTreePaths(TreeNode* root) { string s; if(root != NULL) { s = to_string(root->val); getPath(root,s); } cout << "out if " << endl; return res; } };
相关文章推荐
- ssh整合是遇到问题
- C# XML文档
- 安卓学习:(6)安卓操作sqlite数据库
- C 指针 数组
- 百度面试--内存分配的一个典型程序
- 深度学习(二十一)基于FCN的图像语义分割-CVPR 2015-未完待续
- 关于结构化BOM的思考
- leetcode Merge k Sorted Lists
- [Leetcode]Range Sum Query 2D - Immutable
- 接口开发
- BFS
- Tomcat使用IDEA远程Debug调试
- 我的CS学习路线图
- 贝叶斯决策
- 在Allegro中放置的元件显示不出来E- (SPMHA1-150): Symbol does not fit into the drawing ... reposition the symbol.
- libevent在windows下使用步骤详解
- Linux文件解压
- Google I/O 2014? No,Android I/O 2014
- C#理解AutoResetEvent和ManualResetEvent
- OC Foundation框架—字符串操作方法及习题