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;
    }
};
相关推荐
张太行_42 分钟前
C++中的析构器(Destructor)(也称为析构函数)
开发语言·c++
涛ing5 小时前
32. C 语言 安全函数( _s 尾缀)
linux·c语言·c++·vscode·算法·安全·vim
xrgs_shz6 小时前
MATLAB的数据类型和各类数据类型转化示例
开发语言·数据结构·matlab
独正己身6 小时前
代码随想录day4
数据结构·c++·算法
我不是代码教父8 小时前
[原创](Modern C++)现代C++的关键性概念: 流格式化
c++·字符串格式化·流格式化·cout格式化
利刃大大9 小时前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
子燕若水9 小时前
mac 手工安装OpenSSL 3.4.0
c++
*TQK*9 小时前
ZZNUOJ(C/C++)基础练习1041——1050(详解版)
c语言·c++·编程知识点
Rachela_z9 小时前
代码随想录算法训练营第十四天| 二叉树2
数据结构·算法
细嗅蔷薇@9 小时前
迪杰斯特拉(Dijkstra)算法
数据结构·算法