Binary Tree Paths
2015-09-04 17:35
344 查看
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
[/code]
For example, given the following binary tree:
1 / \ 2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
#include <iostream> #include <string> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; }; struct TreeNode *newNode(int data) { struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode)); node->val = data; node->left = NULL; node->right = NULL; return (node); } class Solution { public: vector<string> res; string s; vector<string> binaryTreePaths(TreeNode* root) { if (root == NULL) return res; if (!root->left&& !root->right) { s.append(to_string(root->val)); res.push_back(s); return res; } help_paths(root, s, res); return res; } void help_paths(TreeNode *root, string &s, vector<string> &res) { if (root->left == NULL && root->right == NULL) { s.append(to_string(root->val)); res.push_back(s); return; } s.append(to_string(root->val)); s.push_back('-'); s.push_back('>'); if (root->left) { help_paths(root->left, s, res); int i = s.size() - 1; for (; i >= 0; i--) { if (s[i] == '>') break; } if (i+1<s.size()) s.erase(s.begin()+1+i, s.end()); } if (root->right) { help_paths(root->right, s, res); int j = s.size() - 1; for (; j >= 0; j--) { if (s[j] == '>') { break; } } if (j + 1<s.size()) s.erase(s.begin()+1+j, s.end()); } int j = s.size() - 1; int count = 0; for (; j >= 0; j--) { if (s[j] == '>') { count++; if (count==2) break; } } if (j + 1<s.size()) s.erase(s.begin() + 1 + j, s.end()); return; } }; int main(int argc, char *argv[]) { struct TreeNode *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(7); vector<string> m; Solution test; m=test.binaryTreePaths(root); for (int i = 0; i < m.size(); ++i) { cout << m[i] << endl; } return 0; }
[/code]
相关文章推荐
- mac 修改文件夹权限.
- 文件和文件夹操作
- 我们的博客,起来嗨
- jQuery权威指南第二版学习笔记(第二章)
- 悲观锁和乐观锁
- OPEN(SAP) UI5 学习入门系列之三:MVC (上) - 模型
- 常见反编译产生错误 k__BackingField 解决办法
- POJ_3280 Cheapest Palindrome(DP)
- 磁盘文件管理(第一部) 后续第二部请等待!!!
- Android笔记(二十一) Android中的Adapter
- 关机/重启/注销
- [Android Pro] android 混淆文件project.properties和proguard-project.txt
- 【Python学习日记】 第四天
- HDU 4545 魔法串
- 网上看的一个SQL需求写的SQL(有点难度哦)
- JPA
- AI(Adobe Illustrator)简单入门——小熊
- 音乐播放器-DAO之MusicUtils
- python相关的一些站点
- Topcoder SRM630,DIV1,500,后缀数组