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

思路

除去根节点,每一层添加->val,然后使用前序遍历的顺序

代码

cpp 复制代码
class Solution {
public:
    vector<string> res;
    void getTreePaths(string s, TreeNode* root){
        s += "->";
        s += to_string(root->val);
        if(root->left == nullptr && root->right == nullptr){
             res.push_back(s);
             return;
        }
        
        if(root->left) getTreePaths(s, root->left);
        if(root->right) getTreePaths(s, root->right);

    }

    vector<string> binaryTreePaths(TreeNode* root) {
        if(root->left == nullptr && root->right == nullptr){
            res.push_back(to_string(root->val));
            return res;
        }
        string s;
        if(root->left) getTreePaths(to_string(root->val), root->left);
        if(root->right) getTreePaths(to_string(root->val), root->right);

        return res;
    }
};
相关推荐
铉铉这波能秀18 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马18 小时前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
我是咸鱼不闲呀18 小时前
力扣Hot100系列20(Java)——[动态规划]总结(下)( 单词拆分,最大递增子序列,乘积最大子数组 ,分割等和子集,最长有效括号)
java·leetcode·动态规划
唐梓航-求职中18 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹18 小时前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll130452529818 小时前
Leetcode二叉树part4
算法·leetcode·职场和发展
颜酱18 小时前
二叉树遍历思维实战
javascript·后端·算法
宝贝儿好19 小时前
第二章: 图像处理基本操作
算法
小陈phd19 小时前
多模态大模型学习笔记(二)——机器学习十大经典算法:一张表看懂分类 / 回归 / 聚类 / 降维
学习·算法·机器学习
@––––––19 小时前
力扣hot100—系列4-贪心算法
算法·leetcode·贪心算法