力扣-二叉树-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;
    }
};
相关推荐
TracyCoder1235 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
u0109272717 小时前
C++中的策略模式变体
开发语言·c++·算法
2501_941837267 小时前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
六义义8 小时前
java基础十二
java·数据结构·算法
四维碎片8 小时前
QSettings + INI 笔记
笔记·qt·算法
Tansmjs8 小时前
C++与GPU计算(CUDA)
开发语言·c++·算法
独自破碎E9 小时前
【优先级队列】主持人调度(二)
算法
weixin_445476689 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王9 小时前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展
Swift社区9 小时前
LeetCode 385 迷你语法分析器
算法·leetcode·职场和发展