每日OJ题_二叉树dfs⑥_力扣257. 二叉树的所有路径

目录

[力扣257. 二叉树的所有路径](#力扣257. 二叉树的所有路径)

解析代码


力扣257. 二叉树的所有路径

257. 二叉树的所有路径

难度 简单

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。

叶子节点 是指没有子节点的节点。

示例 1:

复制代码
输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]

示例 2:

复制代码
输入:root = [1]
输出:["1"]

提示:

  • 树中节点的数目在范围 [1, 100]
  • -100 <= Node.val <= 100
cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {

    }
};

解析代码

思路就是遍历到叶子结点就push当前路径, 到最后剪枝,不用写函数出口。

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    vector<string> ret;
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        dfs(root, "");
        return ret;
    }

    void dfs(TreeNode* root, string path)
    {
        path += to_string(root->val); // 不可能传空root进来
        if(root->left == nullptr && root->right == nullptr)
        {
            ret.push_back(path); // 是叶子结点就push当前路径
        }
        else // 不是叶子结点就先加上箭头
        {
            path += "->";
        }
        if(root->left != nullptr) // 剪枝,此时不用写函数出口
            dfs(root->left, path);
        if(root->right != nullptr)
            dfs(root->right, path);
    }
};
相关推荐
圣保罗的大教堂6 分钟前
leetcode 2799. 统计完全子数组的数目 中等
leetcode
SsummerC13 分钟前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
YuCaiH41 分钟前
数组理论基础
笔记·leetcode·c·数组
尤物程序猿1 小时前
【2025面试Java常问八股之redis】zset数据结构的实现,跳表和B+树的对比
数据结构·redis·面试
2301_807611491 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯
微网兔子2 小时前
伺服器用什么语言开发呢?做什么用什么?
服务器·c++·后端·游戏
YuforiaCode2 小时前
第十三届蓝桥杯 2022 C/C++组 修剪灌木
c语言·c++·蓝桥杯
YOULANSHENGMENG2 小时前
linux 下python 调用c++的动态库的方法
c++·python
CodeWithMe2 小时前
【C++】STL之deque
开发语言·c++
SsummerC2 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划