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;
    }
};
相关推荐
白杨尚青40 分钟前
C++进阶篇(二):多态——虚函数、重写、虚函数表与三个经典坑(附完整代码仓库)
开发语言·c++·多态·虚函数·重写·动态绑定
syagain_zsx1 小时前
spdlog实战:日志分级、滚动与性能调优
linux·c++·日志库·二次开发日志库
zyl76515 小时前
FlashAttention 详解:从 GPU 硬件、普通 Attention 到分块计算与 Online Softmax
算法
爱读书的小胖18 小时前
LeetCode 122:买卖股票的最佳时机 II(C)解题分析
算法
结局无敌18 小时前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
OPEN-F19 小时前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_3077791319 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
AI wins19 小时前
c++新增頭文件
c++
Shadow(⊙o⊙)19 小时前
仿muduo实现高并发服务器——事件就绪管理Channel.hpp
服务器·c++
tomwang032219 小时前
路径优化建模、优化算法分类及工程化小结
算法·数学建模·分类