File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ //Same just reverse in the end.
2+ //Reversing in the end is better than using add(0, E) in case of arraylist as it's an O(1) operation.
3+ class Solution {
4+ public List <List <Integer >> levelOrderBottom (TreeNode root ) {
5+ List <List <Integer >> ans = new ArrayList <>();
6+ if (root == null ) return ans ;
7+ Queue <TreeNode > q = new LinkedList <>();
8+ q .offer (root );
9+ while (!q .isEmpty ()) {
10+ List <Integer > level = new ArrayList <>();
11+ int size = q .size ();
12+ for (int i = 0 ; i <size ; i ++) {
13+ TreeNode cur = q .poll ();
14+ level .add (cur .val );
15+ if (cur .left !=null ) q .offer (cur .left );
16+ if (cur .right !=null ) q .offer (cur .right );
17+ }
18+ ans .add (level );
19+ }
20+ int i = 0 , j = ans .size ()-1 ;
21+ //reverse the list
22+ while (i <j ) {
23+ List <Integer > cur = ans .get (i );
24+ ans .set (i , ans .get (j ));
25+ ans .set (j , cur );
26+ i ++;
27+ j --;
28+ }
29+ return ans ;
30+ }
31+ }
You can’t perform that action at this time.
0 commit comments