当前位置:网站首页>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);
}
}
}
边栏推荐
- Flutter Widget : Flow
- SLF4J 日志门面
- Vulnhub's presidential
- 242. Effective letter heteronyms
- [learning notes] DP status and transfer
- Introduction to the implementation principle of rxjs observable filter operator
- (construction notes) ADT and OOP
- previous permutation lintcode51
- Use of QT OpenGL camera
- SystemVerilog -- OOP -- copy of object
猜你喜欢
随机推荐
Laravel time zone timezone
Vulnhub's Tomato (tomato)
Vulnhub geminiinc V2
Capturing and sorting out external Fiddler -- Conversation bar and filter [2]
[learning notes] DP status and transfer
OpenGL 着色器使用
Duplicate numbers in the array of sword finger offer 03
vulnhub之raven2
(construction notes) ADT and OOP
Php Export word method (One MHT)
Solution à la défaillance de l'installation d'Electron
During FTP login, the error "530 login incorrect.login failed" is reported
Notes on 32-96 questions of sword finger offer
PHP导出word方法(一mht)
PHP导出word方法(一phpword)
Integer string int mutual conversion
Qt OpenGL相机的使用
AOSP ~ NTP (Network Time Protocol)
CGroup introduction
Jsup crawls Baidu Encyclopedia









