Skip to content

Commit aac7430

Browse files
committed
fd
1 parent 83a0db6 commit aac7430

File tree

2 files changed

+20
-20
lines changed

2 files changed

+20
-20
lines changed

leetcode/solution/src/BinaryTreeRightSideView.java

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,33 +5,36 @@
55
public class BinaryTreeRightSideView {
66

77
public List<Integer> rightSideView(TreeNode root) {
8-
List<Integer> result = new LinkedList<Integer>();
8+
List<Integer> result = new LinkedList<>();
99

1010
if (root == null) {
1111
return result;
1212
}
1313

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<>();
1616

17-
queue.add(root);
17+
TreeNode last = null;
18+
19+
queue.offer(root);
1820

1921
while (!queue.isEmpty()) {
2022
TreeNode node = queue.poll();
2123

24+
last = node;
25+
2226
if (node.left != null) {
23-
next.add(node.left);
27+
next.offer(node.left);
2428
}
2529

2630
if (node.right != null) {
27-
next.add(node.right);
31+
next.offer(node.right);
2832
}
2933

3034
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);
3538
}
3639
}
3740

leetcode/src/Main.java

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
public class Main {
66

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<>();
99

1010
if (root == null) {
1111
return result;
@@ -14,33 +14,30 @@ public List<List<Integer>> levelOrderBottom(TreeNode root) {
1414
Queue<TreeNode> queue = new LinkedList<>();
1515
Queue<TreeNode> next = new LinkedList<>();
1616

17-
List<Integer> list = null;
17+
TreeNode last = null;
1818

1919
queue.offer(root);
2020

2121
while (!queue.isEmpty()) {
2222
TreeNode node = queue.poll();
2323

24-
if (list == null) {
25-
list = new ArrayList<>();
26-
}
27-
28-
list.add(node.val);
24+
last = node;
2925

3026
if (node.left != null) {
3127
next.offer(node.left);
3228
}
29+
3330
if (node.right != null) {
3431
next.offer(node.right);
3532
}
3633

3734
if (queue.isEmpty()) {
3835
queue.addAll(next);
3936
next.clear();
40-
result.add(0, list);
41-
list = null;
37+
result.add(last.val);
4238
}
4339
}
40+
4441
return result;
4542
}
4643

0 commit comments

Comments
 (0)