File tree Expand file tree Collapse file tree 2 files changed +28
-25
lines changed Expand file tree Collapse file tree 2 files changed +28
-25
lines changed Original file line number Diff line number Diff line change 26
26
27
27
public class BinaryTreeLevelOrderTraversalII {
28
28
public ArrayList <ArrayList <Integer >> levelOrderBottom (TreeNode root ) {
29
- ArrayList <ArrayList <Integer >> levels = new ArrayList <ArrayList <Integer >>();
29
+ ArrayList <ArrayList <Integer >> ret = new ArrayList <ArrayList <Integer >>();
30
30
if (root == null )
31
- return levels ;
32
- int curr = 1 ;
33
- int next = 0 ;
34
- Queue <TreeNode > q = new LinkedList <TreeNode >();
31
+ return ret ;
35
32
ArrayList <Integer > level = new ArrayList <Integer >();
36
- q .add (root );
37
- while (!q .isEmpty ()) {
38
- TreeNode n = q .poll ();
39
- curr --;
40
- level .add (n .val );
41
- if (n .left != null ) {
42
- q .add (n .left );
43
- next ++;
33
+ Queue <TreeNode > queue = new LinkedList <TreeNode >();
34
+ queue .add (root );
35
+ int currentLevel = 1 ;
36
+ int nextLevel = 0 ;
37
+ while (!queue .isEmpty ()) {
38
+ TreeNode node = queue .remove ();
39
+ level .add (node .val );
40
+ currentLevel --;
41
+ if (node .left != null ) {
42
+ queue .add (node .left );
43
+ nextLevel ++;
44
44
}
45
- if (n .right != null ) {
46
- q .add (n .right );
47
- next ++;
45
+ if (node .right != null ) {
46
+ queue .add (node .right );
47
+ nextLevel ++;
48
48
}
49
- if (curr == 0 ) {
50
- levels .add (level );
49
+ if (currentLevel == 0 ) {
50
+ ret .add (level );
51
51
level = new ArrayList <Integer >();
52
- curr = next ;
53
- next = 0 ;
52
+ currentLevel = nextLevel ;
53
+ nextLevel = 0 ;
54
54
}
55
55
}
56
- ArrayList <ArrayList <Integer >> result = new ArrayList <ArrayList <Integer >>();
57
- for (int i = levels .size () - 1 ; i >= 0 ; i --) {
58
- result .add (levels .get (i ));
56
+ int i = 0 , j = ret .size () - 1 ;
57
+ while (i < j ) {
58
+ ArrayList <Integer > tmp = ret .get (i );
59
+ ret .set (i , ret .get (j ));
60
+ ret .set (j , tmp );
61
+ i ++;
62
+ j --;
59
63
}
60
- return result ;
64
+ return ret ;
61
65
}
62
66
}
Original file line number Diff line number Diff line change 1
-
2
1
/**
3
2
* Given a singly linked list where elements are sorted in ascending order,
4
3
* convert it to a height balanced BST.
You can’t perform that action at this time.
0 commit comments