[勇者闯LeetCode] 257. Binary Tree Paths
来源:互联网 发布:王用汲 知乎 编辑:程序博客网 时间:2024/05/16 19:55
[勇者闯LeetCode] 257. Binary Tree Paths
Description
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"]
Information
- Difficulty: Easy
Solution
遍历二叉树的过程中记录之前的路径,一旦遍历到叶子节点便将该路径加入到结果中。
C++ Code
/** * 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> result; vector<TreeNode*> path; binaryTreePathsRecu(root, &path, &result); return result; } void binaryTreePathsRecu(TreeNode* node, vector<TreeNode*> *path, vector<string> *result) { if (!node) { return; } if (!node->left && !node->right) { string ans = ""; for (const auto &n : *path) { ans.append(to_string(n->val).append("->")); } result->emplace_back(move(ans.append(to_string(node->val)))); } if (node->left) { path->emplace_back(node); binaryTreePathsRecu(node->left, path, result); path->pop_back(); } if (node->right) { path->emplace_back(node); binaryTreePathsRecu(node->right, path, result); path->pop_back(); } }};
阅读全文
0 0
- [勇者闯LeetCode] 257. Binary Tree Paths
- [勇者闯LeetCode] 110. Balanced Binary Tree
- [勇者闯LeetCode] 104. Maximum Depth of Binary Tree
- [勇者闯LeetCode] 107. Binary Tree Level Order Traversal II
- [勇者闯LeetCode] 111. Minimum Depth of Binary Tree
- [勇者闯LeetCode] 100. Same Tree
- [勇者闯LeetCode] 101. Symmetric Tree
- [勇者闯LeetCode] 108. Convert Sorted Array to Binary Search Tree
- [leetcode] 257. Binary Tree Paths
- 257. Binary Tree Paths LeetCode
- 【LeetCode】257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- LeetCode *** 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- Leetcode 257. Binary Tree Paths
- LeetCode-257.Binary Tree Paths
- 【leetcode】257. Binary Tree Paths
- Redis集群原理简述
- TaskRecord、ActivityRecord 和 ActivityStack的关系
- 【机器人学的数学基础】(1)李群、李代数和螺旋运动
- java实现字符串加密
- 使用eclipse和maven生成java web程序war包
- [勇者闯LeetCode] 257. Binary Tree Paths
- springMVC中controller的几种返回类型
- 【CSS】padding,border,margin与width宽度的关系
- redis集群-虚拟机测试(针对有redis基础的人群)
- ubuntu 14.04上Samba服务失败的问题
- 浅谈安卓studio之断点调试
- Java Concurrency代码实例之四-锁
- 06-mysql中的查询(排序、聚合函数、分组、分页)(第二章)
- swift可视化自定义控件