257. Binary Tree Paths
来源:互联网 发布:有口碑的淘宝cos店 编辑:程序博客网 时间:2024/05/22 12:16
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"]
solution:
/** * 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; traverse(root, res); return res; } void traverse(TreeNode *root, vector<string> &res){ if(!root) return; if(res.size()==0) res.push_back(string()); if(!root->left&&!root->right){ res[res.size()-1] += to_string(root->val); } if(root->left&&!root->right){ res[res.size()-1] += to_string(root->val)+"->"; traverse(root->left,res); } if(root->right&&!root->left){ res[res.size()-1] += to_string(root->val)+"->"; traverse(root->right,res); } if(root->right&&root->left){ res[res.size()-1] += to_string(root->val)+"->"; string tmp = res[res.size()-1]; traverse(root->left,res); res.push_back(tmp); traverse(root->right,res); } }};
心得:思路比较简单
运行速度快
0 0
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- Android Weak Handler:可以避免内存泄漏的Handler库
- Fiddler 会拉弦的程序员
- xib自定义View
- 使用gdi+裁剪圆形图像
- 访问arcgisserver管理页面报scriptResourceHandler配置错误
- 257. Binary Tree Paths
- redis分布式锁-SETNX实现
- How to concatenate two matrices in Python?
- java spring mvc时间String转Date(二)
- MyBatis 基于接口编程学习笔记
- [Spring]02_Spring框架和MVC原理
- python爬虫(抓取百度新闻列表)
- 默认创建两个桌面图标
- nuget自动打包及发布nuget自有服务器