LeetCode C++ 257. Binary Tree Paths【Tree】简单
发布日期:2021-07-01 02:50:21 浏览次数:2 分类:技术文章

本文共 1174 字,大约阅读时间需要 3 分钟。

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:   1 /   \2     3 \  5Output: ["1->2->5", "1->3"]Explanation: All root-to-leaf paths are: 1->2->5, 1->3

题意:给定一个二叉树,返回所有从根节点到叶子节点的路径的字符串表示。


思路:就是一个递归的题目。明确递归函数 binaryTreePaths 的语义是:返回以 root 为根结点的到叶子结点的路径字符串。然后按照二叉树的递归形态进行讨论即可。

代码:

class Solution {
public: vector
binaryTreePaths(TreeNode* root) {
vector
res; if (root == nullptr) return res; if (root->left == nullptr && root->right == nullptr) {
res.push_back(to_string(root->val)); return res; } //获得以root为根结点的二叉树中,所有从根结点到每个叶子结点的字符串 vector
leftStr = binaryTreePaths(root->left); for (int i = 0; i < leftStr.size(); ++i) res.push_back(to_string(root->val) + "->" + leftStr[i]); vector
rightStr = binaryTreePaths(root->right); for (int i = 0; i < rightStr.size(); ++i) res.push_back(to_string(root->val) + "->" + rightStr[i]); return res; }};

效率:

执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户内存消耗:13.6 MB, 在所有 C++ 提交中击败了74.43% 的用户

转载地址:https://memcpy0.blog.csdn.net/article/details/108249533 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode C++ 17. Letter Combinations of a Phone Number【DFS/Backtracking】中等
下一篇:HDU 1711 Number Sequence【字符串】

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年05月05日 16时41分52秒