已解决
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%的人还看了
相似问题
- 【洛谷 B2003】输出第二个整数 题解(顺序结构+输入输出)
- 20天拿下华为OD笔试之【模拟】2023B-数大雁【欧弟算法】全网注释最详细分类最全的华为OD真题题解
- Centos(Linux)服务器安装Dotnet8 及 常见问题解决
- 【蓝桥杯选拔赛真题23】C++计算24 第十二届蓝桥杯青少年创意编程大赛C++编程选拔赛真题解析
- [github配置] 远程访问仓库以及问题解决
- 电子学会C/C++编程等级考试2022年06月(一级)真题解析
- [github初学者教程] 分支管理-以及问题解决
- Flume的安装部署及常见问题解决
- 电子学会C/C++编程等级考试2022年03月(一级)真题解析
- 2023年咸阳市《网络建设与运维》赛题解析------四、安全配置
猜你感兴趣
版权申明
本文"LeetCode257. Binary Tree Paths":http://eshow365.cn/6-38354-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!