当前位置:网站首页>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);
}
}
}
边栏推荐
猜你喜欢
随机推荐
vulnhub之Ripper
vulnhub之tomato(西红柿)
Raven2 of vulnhub
在网上炒股开户可以吗?资金安全吗?
Unicode encoding table download
OpenGL shader use
Vulnhub's cereal
安装electron失败的解决办法
Simple factory and factory method mode
How to deploy web pages to Alibaba cloud
vulnhub之GeminiInc v2
Itext7 uses iexternalsignature container for signature and signature verification
Qt+vtk+occt reading iges/step model
DEJA_VU3D - Cesium功能集 之 053-地下模式效果
Shutter widget: centerslice attribute
Pki/ca and digital certificate
Why can't my MySQL container start
PHP导出word方法(一mht)
(构造笔记)GRASP学习心得
Wechat applet development - page Jump transfer parameters







![[learning notes] DP status and transfer](/img/5e/59c64d2fe08b89fba2d7e1e6de2761.png)
