当前位置:首页 > 编程笔记 > 正文
已解决

LeetCode257. Binary Tree Paths

来自网友在路上 147847提问 提问时间:2023-11-12 19:28:43阅读次数: 47

最佳答案 问答题库478位专家为你答疑解惑

文章目录

    • 一、题目
    • 二、题解

一、题目

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

二、题解

前序遍历+回溯

/*** 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;}
};
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"LeetCode257. Binary Tree Paths":http://eshow365.cn/6-38354-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!