Leetcode题 257. Binary Tree Paths
来源:互联网 发布:旅贸通软件 编辑:程序博客网 时间:2024/06/18 12:44
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"]
代码如下:
/** * 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: //按照容易自己习惯的数据结构来存储路径,最后做一个转换 void findPath(TreeNode* t,vector<int>& temp, vector<vector<int> >& record) { temp.push_back(t->val); if(t->left!=NULL) findPath(t->left, temp, record); if(t->right!=NULL) findPath(t->right, temp, record); //到达叶子节点,就记录路径 if(t->left==NULL && t->right==NULL) { record.push_back(temp); temp.erase(temp.end()-1); return ; } //中间节点返回 temp.erase(temp.end()-1); return; } vector<string> binaryTreePaths(TreeNode* root) { vector<vector<int>> record; vector<string> srecord; if(root==NULL) return srecord; vector<int> temp; //找到所有的路 findPath(root,temp,record); //把所有的路按照题目要求存储 string stemp; for(int i=0;i<record.size();i++) { stringstream ss; for(int j=0;j<record[i].size();j++) { ss<<record[i][j]<<"->"; } stemp.clear(); stemp=ss.str(); //去掉最后的"->" stemp.pop_back(); stemp.pop_back(); srecord.push_back(stemp); } return srecord; }};
0 0
- Leetcode题 257. Binary Tree Paths
- [leetcode] 257. Binary Tree Paths
- 257. Binary Tree Paths LeetCode
- 【LeetCode】257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- LeetCode *** 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- Leetcode 257. Binary Tree Paths
- LeetCode-257.Binary Tree Paths
- 【leetcode】257. Binary Tree Paths
- [Leetcode]257. Binary Tree Paths
- LeetCode - 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- [leetcode] 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- 257.[Leetcode]Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- Django模型操作常用方法总结
- 海量数据处理——推荐文章
- MySQL数据库的入门(一)
- Mybatis面向接口编程
- Maven实战(Maven In Action)
- Leetcode题 257. Binary Tree Paths
- tjut 4699
- 顺时针打印矩阵
- HDU_1114_Piggy-Bank(完全背包)
- LintCode笔记(8)——丑数II
- Jsp---JSTL
- 提高工作效率篇之命令行版的 Alfred —— z
- 指针,调用,返回
- RuntimeViewer ver 1.01