File tree Expand file tree Collapse file tree 1 file changed +39
-2
lines changed Expand file tree Collapse file tree 1 file changed +39
-2
lines changed Original file line number Diff line number Diff line change @@ -28,9 +28,46 @@ return its bottom-up level order traversal as:
2828** Tags:**  Tree, Breadth-first Search
2929
3030
31- ## 思路  
31+ ## 思路0  
3232
33- 题意是从下往上按层遍历二叉树,每一层是从左到右,由于是从下往上,那么我们就先遍历,当链表尺寸小于深度的时候,我们在链表首部插入新的节点,然后在最后遍历完插入节点即可,好好模拟想一想,画一画,应该能想通。
33+ 题意是从下往上按层遍历二叉树,每一层是从左到右,按层遍历,很明显,宽搜第一时间符合,因为是从下往上,所以插入的时候每次插到链表头即可。
34+ 
35+ 
36+ ```  java 
37+ /** 
38+  * Definition for a binary tree node. 
39+  * public class TreeNode { 
40+  * int val; 
41+  * TreeNode left; 
42+  * TreeNode right; 
43+  * TreeNode(int x) { val = x; } 
44+  * } 
45+  */  
46+ class  Solution  {
47+  public  List<List<Integer > >  levelOrderBottom (TreeNode  root ) {
48+  if  (root ==  null ) return  Collections . emptyList();
49+  List<List<Integer > >  list =  new  LinkedList<> ();
50+  LinkedList<TreeNode >  q =  new  LinkedList<> ();
51+  q. add(root);
52+  while (! q. isEmpty()) {
53+  int  size =  q. size();
54+  List<Integer >  sub =  new  LinkedList ();
55+  for (int  i =  0 ; i <  size; ++ i) {
56+  TreeNode  node =  q. remove();
57+  sub. add(node. val);
58+  if  (node. left !=  null ) q. add(node. left);
59+  if  (node. right !=  null ) q. add(node. right);
60+  }
61+  list. add(0 , sub);
62+  }
63+  return  list;
64+  }
65+ }
66+ ``` 
67+ 
68+ ## 思路1  
69+ 
70+ 另一种思路就是深搜,深搜的时候同时记录深度,然后在相应的层插入节点值即可。
3471
3572```  java 
3673/** 
                         You can’t perform that action at this time. 
           
                  
0 commit comments