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;
    }
};
相关推荐
一拳一个呆瓜1 小时前
【STL】_SCL_SECURE_NO_WARNINGS
c++·stl
小小编程路2 小时前
C++ 异常 完整讲解
开发语言·c++
一只齐刘海的猫4 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏1114 小时前
数据结构 | 八大排序
数据结构·算法·排序算法
Frank学习路上5 小时前
【C++】面试:关键字与语法特性
c++·面试
liulilittle5 小时前
固定数组时间轮的槽过载优化:桶链表与批次执行
网络·数据结构·链表
IronMurphy5 小时前
【算法五十七】146. LRU 缓存
算法·缓存
Irissgwe6 小时前
数据结构-栈和队列
数据结构·c++·c·栈和队列
两片空白6 小时前
数据容器集合set/frozenset
数据结构