257. Binary Tree Paths
来源:互联网 发布:成都java培训费用多少 编辑:程序博客网 时间:2024/06/08 20:08
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"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
/** * 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 __binaryTreePaths(TreeNode* root, string str, vector<string>& res){if(!root){res.push_back(str);return;}str += to_string(root->val);if(!root->left && !root->right){__binaryTreePaths(root->right, str, res);}if(root->left){__binaryTreePaths(root->left, str + "->", res);}if(root->right){__binaryTreePaths(root->right, str + "->", res);}}vector<string> binaryTreePaths(TreeNode* root) {string str;vector<string> res;if(root){__binaryTreePaths(root, str, res);}return res;}};
写的还是不简洁
void binaryTreePaths(vector<string>& result, TreeNode* root, string t) { if(!root->left && !root->right) { result.push_back(t); return; } if(root->left) binaryTreePaths(result, root->left, t + "->" + to_string(root->left->val)); if(root->right) binaryTreePaths(result, root->right, t + "->" + to_string(root->right->val));}vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; if(!root) return result; binaryTreePaths(result, root, to_string(root->val)); return result;}
阅读全文
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
- 注册页面数据校验(JS基本语法)
- 上传图片预览JS脚本 Input file图片预览的实现示例
- div实现绑定按键事件
- iOS视频边下边播–缓存数据流(备用知识点)
- css持续旋转
- 257. Binary Tree Paths
- spark自定义分区
- RxJava学习资料整理
- 各种功能的开源项目
- 关于12/24时间制的一些代码
- Android RxJava2+Retrofit2搭建网络请求框架
- 用jquery有用的功能
- Gradle2.0用户指南翻译——第五章. 疑难解答
- 高速公路ETC卡签之我见2-卡片消费