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;
    }
};
相关推荐
Swift社区几秒前
Swift 解法详解 LeetCode 362:敲击计数器,让数据统计更高效
开发语言·leetcode·swift
ajassi20004 分钟前
开源 C++ QT Widget 开发(十三)IPC通讯--本地套接字 (Local Socket)
linux·c++·qt·开源
Q741_14710 分钟前
C++ 前缀和 高频笔试考点 实用技巧 牛客 DP34 [模板] 前缀和 题解 每日一题
开发语言·c++·算法·前缀和·牛客网
YaoYuan932314 分钟前
C++ 容器——unordered_xxx
c++
凤年徐1 小时前
C++类和对象(上):从设计图到摩天大楼的构建艺术
c语言·开发语言·c++·类和对象
lifallen1 小时前
Kafka 内存池MemoryPool 设计
数据结构·kafka·apache
RTC老炮1 小时前
webrtc弱网-LossBasedBandwidthEstimation类源码分析与算法原理
网络·算法·webrtc
豆浩宇2 小时前
Conda环境隔离和PyCharm配置,完美同时运行PaddlePaddle和PyTorch
人工智能·pytorch·算法·计算机视觉·pycharm·conda·paddlepaddle
一只鱼^_2 小时前
牛客周赛 Round 108
数据结构·c++·算法·动态规划·图论·广度优先·推荐算法
小刘的AI小站3 小时前
leetcode hot100 二叉搜索树
算法·leetcode