力扣-二叉树-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;
    }
};
相关推荐
Liangwei Lin13 分钟前
LeetCode 74. 搜索二维矩阵
算法·leetcode·矩阵
phltxy17 分钟前
Redis Hash 数据类型:详解命令与实战场景
redis·算法·哈希算法
放羊郎8 小时前
基于ORB-SLAM2算法的优化工作
人工智能·算法·计算机视觉
mask哥8 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
如果'\'真能转义说8 小时前
OOXML 文档格式剖析:哈希、ZIP结构与识别
xml·算法·c#·哈希算法
梦梦代码精10 小时前
BuildingAI 上部署自定义工作流智能体:5 个实用技巧
大数据·人工智能·算法·开源软件
Zephyr_011 小时前
Leedcode算法题
java·算法
流年如夢11 小时前
栈和列队(LeetCode)
数据结构·算法·leetcode·链表·职场和发展
Hello.Reader12 小时前
算法基础(十)——分治思想把大问题拆成小问题
java·开发语言·算法