File tree Expand file tree Collapse file tree 2 files changed +20
-20
lines changed Expand file tree Collapse file tree 2 files changed +20
-20
lines changed Original file line number Diff line number Diff line change 5
5
public class BinaryTreeRightSideView {
6
6
7
7
public List <Integer > rightSideView (TreeNode root ) {
8
- List <Integer > result = new LinkedList <Integer >();
8
+ List <Integer > result = new LinkedList <>();
9
9
10
10
if (root == null ) {
11
11
return result ;
12
12
}
13
13
14
- Queue <TreeNode > queue = new LinkedList <TreeNode >();
15
- Queue <TreeNode > next = new LinkedList <TreeNode >();
14
+ Queue <TreeNode > queue = new LinkedList <>();
15
+ Queue <TreeNode > next = new LinkedList <>();
16
16
17
- queue .add (root );
17
+ TreeNode last = null ;
18
+
19
+ queue .offer (root );
18
20
19
21
while (!queue .isEmpty ()) {
20
22
TreeNode node = queue .poll ();
21
23
24
+ last = node ;
25
+
22
26
if (node .left != null ) {
23
- next .add (node .left );
27
+ next .offer (node .left );
24
28
}
25
29
26
30
if (node .right != null ) {
27
- next .add (node .right );
31
+ next .offer (node .right );
28
32
}
29
33
30
34
if (queue .isEmpty ()) {
31
- result .add (node .val );
32
- Queue <TreeNode > temp = queue ;
33
- queue = next ;
34
- next = temp ;
35
+ queue .addAll (next );
36
+ next .clear ();
37
+ result .add (last .val );
35
38
}
36
39
}
37
40
Original file line number Diff line number Diff line change 4
4
5
5
public class Main {
6
6
7
- public List <List < Integer >> levelOrderBottom (TreeNode root ) {
8
- List <List < Integer > > result = new LinkedList <>();
7
+ public List <Integer > rightSideView (TreeNode root ) {
8
+ List <Integer > result = new LinkedList <>();
9
9
10
10
if (root == null ) {
11
11
return result ;
@@ -14,33 +14,30 @@ public List<List<Integer>> levelOrderBottom(TreeNode root) {
14
14
Queue <TreeNode > queue = new LinkedList <>();
15
15
Queue <TreeNode > next = new LinkedList <>();
16
16
17
- List < Integer > list = null ;
17
+ TreeNode last = null ;
18
18
19
19
queue .offer (root );
20
20
21
21
while (!queue .isEmpty ()) {
22
22
TreeNode node = queue .poll ();
23
23
24
- if (list == null ) {
25
- list = new ArrayList <>();
26
- }
27
-
28
- list .add (node .val );
24
+ last = node ;
29
25
30
26
if (node .left != null ) {
31
27
next .offer (node .left );
32
28
}
29
+
33
30
if (node .right != null ) {
34
31
next .offer (node .right );
35
32
}
36
33
37
34
if (queue .isEmpty ()) {
38
35
queue .addAll (next );
39
36
next .clear ();
40
- result .add (0 , list );
41
- list = null ;
37
+ result .add (last .val );
42
38
}
43
39
}
40
+
44
41
return result ;
45
42
}
46
43
You can’t perform that action at this time.
0 commit comments