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;
    }
};
相关推荐
黑听人几秒前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode
位东风18 分钟前
【c++学习记录】状态模式,实现一个登陆功能
c++·学习·状态模式
hans汉斯20 分钟前
【人工智能与机器人研究】基于力传感器坐标系预标定的重力补偿算法
人工智能·算法·机器人·信号处理·深度神经网络
vortex52 小时前
算法设计与分析:分治、动态规划与贪心算法的异同与选择
算法·贪心算法·动态规划
前端拿破轮2 小时前
🤡🤡🤡面试官:就你这还每天刷leetcode?连四数相加和四数之和都分不清!
算法·leetcode·面试
雷羿 LexChien2 小时前
C++内存泄漏排查
开发语言·c++
地平线开发者3 小时前
征程 6|工具链量化简介与代码实操
算法·自动驾驶
嘉小华3 小时前
CMake 完全指南:第一章 - 构建的烦恼 - 为什么需要CMake?
c++
DoraBigHead3 小时前
🧠 小哆啦解题记——谁偷改了狗狗的台词?
算法
Kaltistss3 小时前
240.搜索二维矩阵Ⅱ
线性代数·算法·矩阵