Binary Tree Paths
来源:互联网 发布:seo推广 编辑:程序博客网 时间:2024/06/06 01:29
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 intToStr(int i) { stringstream ss; ss<<i; return ss.str(); }
简单的辅助函数,用来将int转换成sring。
void searchBT(TreeNode *root,string &path,vector<string> &ans) { if(!root->left && !root->right) ans.push_back(path + intToStr(root->val)); if(root->left) { string s = path + intToStr(root->val)+"->"; searchBT(root->left,s,ans); } if(root->right) { string s = path + intToStr(root->val)+"->"; searchBT(root->right,s,ans); } }
主要的辅助函数。
如果当前的结点没有左右孩子,则直接将当前的path后追加当前结点的值后存入vector中。
如果当前的结点有左子树,则在当前path后追加当前结点的值后,对左子树调用该函数。
如果当前的结点有右子树,则在当前的path后追加当前结点的值后,对右子树调用该函数。
/** * 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> ret; if(root) { string path=""; searchBT(root,path,ret); } return ret; } private: string intToStr(int i) { stringstream ss; ss<<i; return ss.str(); } void searchBT(TreeNode *root,string &path,vector<string> &ans) { if(!root->left && !root->right) ans.push_back(path + intToStr(root->val)); if(root->left) { string s = path + intToStr(root->val)+"->"; searchBT(root->left,s,ans); } if(root->right) { string s = path + intToStr(root->val)+"->"; searchBT(root->right,s,ans); } }};
0 0
- Binary Tree Paths
- Leetcode: Binary Tree Paths
- [LeetCode] Binary Tree Paths
- [Leetcode]Binary Tree Paths
- leetcode:Binary Tree Paths
- Binary Tree Paths
- [leetcode] Binary Tree Paths
- 257 Binary Tree Paths
- Binary Tree Paths
- [LeetCode257] Binary Tree Paths
- Binary Tree Paths
- Binary Tree Paths
- Leetcode: Binary Tree Paths
- LeetCode:Binary Tree Paths
- leetcode Binary Tree Paths
- leetcode Binary Tree Paths
- LeetCode:Binary Tree Paths
- Binary Tree Paths
- hdoj 最长回文 3068 (字符串&manacher)
- css中IE判断语句 if !IE
- js实现textarea的剩余字数动态提示效果demo
- iPhone6 开启4G
- 点滴 UL
- Binary Tree Paths
- 使用java运行javaScript脚本
- 《计算机技术领域当前的主流技术及其社会需求调查报告》
- 升级到安卓5.0后,和包提示:“检测到您的手机或sim卡不完全支持和包业务,部分NFC相关功能将无法正常使用”的问题解决办法
- windows批处理
- Selector属性说明
- Windows通信端口初始化失败
- Android6.0的phone应用源码分析(1)——智能手机的硬件结构介绍
- 触发器