LeetCode257. Binary Tree Paths

文章目录

一、题目

Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

Example 1:

Input: root = [1,2,3,null,5]

Output: ["1->2->5","1->3"]

Example 2:

Input: root = [1]

Output: ["1"]

Constraints:

The number of nodes in the tree is in the range [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:
    void getPath(TreeNode* root,vector<int>& path,vector<string>& res){
        path.push_back(root->val);
        if(root->left == nullptr && root->right == nullptr){
            string s;
            for(int i = 0;i < path.size();i++){
                s += to_string(path[i]);
                if(i != path.size() - 1) s += "->";
            }
            res.push_back(s);
        }
        if(root->left){
            getPath(root->left,path,res);
            path.pop_back();
        }
        if(root->right){
            getPath(root->right,path,res);
            path.pop_back();
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<int> path;
        vector<string> res;
        getPath(root,path,res);
        return res;
    }
};
相关推荐
CHANG_THE_WORLD1 分钟前
C语言中的 %*s 和 %.*s 和C++的字符串格式化输出
c语言·c++·c#
绛橘色的日落(。・∀・)ノ10 分钟前
机器学习之评估与偏差方差分析
算法
消失的旧时光-194317 分钟前
C语言对象模型系列(四)《Linux 内核里的 container_of 到底是什么黑魔法?》—— 一篇讲透 Linux 内核的“对象模型”核心技巧
linux·c语言·算法
AI_Ming1 小时前
从0开始学AI:层归一化,原来是这回事!
算法·ai编程
WL_Aurora1 小时前
备战蓝桥杯国赛【Day 8】
算法·蓝桥杯
螺丝钉的扭矩一瞬间产生高能蛋白1 小时前
QT的C++接口基础用法
c++·qt·嵌入式软件·嵌入式linux·linux应用
智者知已应修善业1 小时前
【51单片机模拟生日蜡烛】2023-10-10
c++·经验分享·笔记·算法·51单片机
MediaTea1 小时前
Scikit-learn:从数据到结构——无监督学习的最小闭环
人工智能·学习·算法·机器学习·scikit-learn
智者知已应修善业2 小时前
【51单片机如何让LED灯从一亮到八,再从八亮到一】2023-10-13
c++·经验分享·笔记·算法·51单片机
qeen872 小时前
【数据结构】二叉树相关经典函数C语言实现
c语言·数据结构·c++·笔记·学习·算法·二叉树