[leetcode]257. Binary Tree Paths
来源:互联网 发布:js setdata 编辑:程序博客网 时间:2024/05/20 09:23
题目来源:https://leetcode.com/problems/binary-tree-paths/
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"]方法一:
class Solution {public: vector<string> binaryTreePaths(TreeNode *root) { std::vector<int> path; std::vector<std::vector<int>> result; std::vector<std::string> rec; if(root==NULL) return rec; preTraverse(root, path, result); for(std::vector<int> tmp:result) { std::string s(std::to_string(tmp[0])); for(int i=1;i<tmp.size();i++) s=s+"->"+std::to_string(tmp[i]); rec.push_back(s); } return rec; } void preTraverse(TreeNode *root,std::vector<int> path,std::vector<std::vector<int>> &result) { if(root==NULL) return; path.push_back(root->val); if(root->left==NULL && root->right==NULL) { result.push_back(path); return; } if(root->left) preTraverse(root->left,path,result); if(root->right) preTraverse(root->right,path,result); path.pop_back(); }
方法二:
class Solution{public: vector<string> binaryTreePaths(TreeNode * root) { vector<string> res; if(root) dfs(root,"",res); return res; } void dfs(TreeNode *root,string out,vector<string> &res) { out+=to_string(root->val); if(root->left==NULL && root->right==NULL) res.push_back(out); else { if(root->left) dfs(root->left,out+"->",res); if(root->right) dfs(root->right,out+"->",res); } }};
0 0
- [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
- leetcode 257. Binary Tree Paths
- oj-7-E-方程求解
- C病毒
- JavaScript中,对象需不需要加引号?
- 一元多项式
- Java 8 Streams 中的数据库 CRUD 操作
- [leetcode]257. Binary Tree Paths
- 用lfw99.9的提取出来的特征在wuxiang的上面测试出来的结果
- android——彻底关闭——应用程序
- oj-7-F-奖金总数
- coturn(turn)服务器搭建
- Windows下安装Elasticsearch 5.0.0遇到的问题
- chmod-修改文件权限
- 文本分类
- Java回顾之集合