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;
    }
};
相关推荐
方传旺5 分钟前
C++17 std::optional 深拷贝 vs 引用:unordered_map 查询大对象性能对比
c++
Dontla20 分钟前
Makefile介绍(Makefile教程)(C/C++编译构建、自动化构建工具)
c语言·c++·自动化
Xの哲學25 分钟前
Perf使用详解
linux·网络·网络协议·算法·架构
奶黄小甜包31 分钟前
C语言零基础第18讲:自定义类型—结构体
c语言·数据结构·笔记·学习
想不明白的过度思考者35 分钟前
数据结构(排序篇)——七大排序算法奇幻之旅:从扑克牌到百亿数据的魔法整理术
数据结构·算法·排序算法
小七rrrrr41 分钟前
动态规划法 - 53. 最大子数组和
java·算法·动态规划
code小毛孩1 小时前
leetcodehot100 矩阵置零
算法
一支闲人1 小时前
C语言相关简单数据结构:双向链表
c语言·数据结构·链表·基础知识·适用于新手小白
何妨重温wdys1 小时前
矩阵链相乘的最少乘法次数(动态规划解法)
c++·算法·矩阵·动态规划
重启的码农1 小时前
ggml 介绍 (6) 后端 (ggml_backend)
c++·人工智能·神经网络