leetcode_c++:树:Binary Tree Paths(257)
来源:互联网 发布:暖男的同义网络词 编辑:程序博客网 时间:2024/05/22 13:36
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \2 3 \ 5
求跟到叶子的所有路径。
分析:
直接 DFS 过去求求行了,也就是前序+记录路径。
class Solution {public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> ans; vector<int> path; dfs(root, path, ans); return ans; }private: void dfs(TreeNode* root, vector<int> &path, vector<string> &ans) { if (!root) return; path.push_back(root->val); if (!root->left && !root->right) ans.push_back(getString(path)); dfs(root->left, path, ans); dfs(root->right, path, ans); path.pop_back(); } string getString(vector<int> path) { if (path.empty()) return ""; string ret; for (int i = 0; i < path.size() - 1; ++i) ret += to_string(path[i]) + "->"; ret += to_string(path[path.size() - 1]); return ret; }};
0 0
- leetcode_c++:树:Binary Tree Paths(257)
- leetcode_c++:树:Balanced Binary Tree(110)
- 257 Binary Tree Paths
- 257 Binary Tree Paths
- 257 Binary Tree Paths
- [257]Binary Tree Paths
- 257、Binary Tree Paths
- 257 Binary Tree Paths
- leetcode_c++:树: Minimum Depth of Binary Tree(111)
- leetcode_c++:树: Flatten Binary Tree to Linked List(114)
- leetcode_c++:树:Serialize and Deserialize Binary Tree(297)
- leetcode_c++:树:Validate Binary Search Tree(098)
- leetcode_c++:树:Recover Binary Search Tree(099)
- leetcode_c++:树:Invert Binary Tree(226 )
- LeetCode(257)Binary Tree Paths
- leetcode 257: Binary Tree Paths
- leetCode #257 Binary Tree Paths
- LeetCode(257)Binary Tree Paths
- Topic Model
- 欢迎使用CSDN-markdown编辑器
- 如何用Solr搭建大数据查询平台
- iOS tableView editCell 删除Cell 置顶Cell NSIndexPath写法
- linux 文本编辑工具
- leetcode_c++:树:Binary Tree Paths(257)
- centos使用l2tp协议连接vpn服务器
- 冒泡法排序详细过程
- Android开发之RecyclerView全解
- oracle日期的查询和插入
- suricata在netmap模式用autofp方式抓包有内存泄漏的相关信息
- MySQL外键的注意事项
- fasttext
- 3.单例模式的多种写法