力扣-二叉树-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;
    }
};
相关推荐
Savior`L2 小时前
二分算法及常见用法
数据结构·c++·算法
mmz12072 小时前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻3 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习4 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~4 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法
AndrewHZ4 小时前
【遥感图像入门】DEM数据处理核心算法与Python实操指南
图像处理·python·算法·dem·高程数据·遥感图像·差值算法
CoderYanger5 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习5 小时前
面试150——第二周
数据结构·算法·leetcode
liu****5 小时前
3.链表讲解
c语言·开发语言·数据结构·算法·链表