当前位置:网站首页>257. All paths of binary tree
257. All paths of binary tree
2022-07-03 12:13:00 【zwanying】
subject
Give you the root node of a binary tree root , Press In any order , Return all paths from the root node to the leaf node .
Leaf node A node without children .
Example 1:
Input :root = [1,2,3,null,5]
Output :[“1->2->5”,“1->3”]
Example 2:
Input :root = [1]
Output :[“1”]
Tips :
The number of nodes in the tree is in the range [1, 100] Inside
-100 <= Node.val <= 100
Their thinking
Find the way , It seems that there is something wrong with traversal no matter how :
After finding the first leaf node , How to get back , Continue to traverse the next leaf Node ? This requires backtracking .
Record the traversed path with an array , Find the leaf node , Go back to the previous node .
Use recursion to solve , Where to recurse , Where to go back .
Code implementation
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<Integer> list = new ArrayList<>();
List<String> result = new ArrayList<>();
if(root == null) return result;
digui(list,result,root);
return result;
}
void digui(List<Integer> list,List<String> result,TreeNode r){
list.add(r.val);
if( r.left ==null && r.right == null){
String ss = "";
for(int i=0;i<list.size();i++){
ss = ss + Integer.toString(list.get(i));
if(i!=list.size()-1){
ss = ss + "->";
}
}
result.add(ss);
return;
}
if(r.left != null){
digui(list,result,r.left);
list.remove(list.size()-1);
}
if(r.right != null){
digui(list,result,r.right);
list.remove(list.size()-1);
}
}
}
边栏推荐
- Systemverilog-- OOP--对象的拷贝
- During FTP login, the error "530 login incorrect.login failed" is reported
- Ripper of vulnhub
- New features of ES6
- vulnhub之pyexp
- Interview experience in summer camp of Central South University in 2022
- Concurrent programming - singleton
- MySQL uses the method of updating linked tables with update
- vulnhub之Nagini
- DEJA_VU3D - Cesium功能集 之 053-地下模式效果
猜你喜欢
MCDF Experiment 1
Visual studio 2022 downloading and configuring opencv4.5.5
Flutter 退出登录二次确认怎么做才更优雅?
Groovy test class and JUnit test
Shutter: add gradient stroke to font
Summary of development issues
Symlink(): solution to protocol error in PHP artisan storage:link on win10
vulnhub之Ripper
Vulnhub geminiinc V2
Develop plug-ins for idea
随机推荐
vulnhub之pyexp
Swagger
242. Effective letter heteronyms
(构造笔记)ADT与OOP
laravel 时区问题timezone
QT OpenGL texture map
[official MySQL document] deadlock
(数据库提权——Redis)Redis未授权访问漏洞总结
PHP export word method (phpword)
Pragma pack syntax and usage
typeScript
CGroup introduction
Vulnhub pyexp
Shardingsphere sub database and sub table < 3 >
Qt OpenGL相机的使用
Ripper of vulnhub
Unicode encoding table download
vulnhub之Nagini
Duplicate numbers in the array of sword finger offer 03
MCDF Experiment 1