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;
    }
};
相关推荐
点云SLAM2 分钟前
C++设计模式之单例模式(Singleton)以及相关面试问题
c++·设计模式·面试·c++11·单例模式(singleton)
neardi临滴科技2 分钟前
从算法逻辑到芯端落地:YOLO 目标检测的进化与瑞芯微实践
算法·yolo·目标检测
小雨下雨的雨3 分钟前
Flutter跨平台开发实战:鸿蒙系列-循环交互艺术系列——瀑布流:不规则网格的循环排布算法
算法·flutter·华为·交互·harmonyos·鸿蒙系统
小雨下雨的雨5 分钟前
Flutter跨平台开发实战: 鸿蒙与循环交互艺术:跑马灯的无极滚动算法
算法·flutter·华为·交互·harmonyos·鸿蒙
草莓熊Lotso8 分钟前
Qt 信号与槽深度解析:从基础用法到高级实战(含 Lambda 表达式)
java·运维·开发语言·c++·人工智能·qt·数据挖掘
脏脏a1 小时前
C++ STL list 模拟实现:从底层链表到容器封装
开发语言·c++·stl·双链表
charliejohn3 小时前
计算机考研 408 数据结构 树形查找 相关概念及计算题例题
数据结构·考研
NAGNIP8 小时前
一文搞懂机器学习中的特征降维!
算法·面试
NAGNIP8 小时前
一文搞懂机器学习中的特征构造!
算法·面试
Learn Beyond Limits9 小时前
解构语义:从词向量到神经分类|Decoding Semantics: Word Vectors and Neural Classification
人工智能·算法·机器学习·ai·分类·数据挖掘·nlp