Skip to content

Commit c98dabb

Browse files
committed
refine
1 parent a3cfa6d commit c98dabb

File tree

2 files changed

+28
-25
lines changed

2 files changed

+28
-25
lines changed

BinaryTreeLevelOrderTraversalII.java

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -26,37 +26,41 @@
2626

2727
public class BinaryTreeLevelOrderTraversalII {
2828
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>>();
3030
if (root == null)
31-
return levels;
32-
int curr = 1;
33-
int next = 0;
34-
Queue<TreeNode> q = new LinkedList<TreeNode>();
31+
return ret;
3532
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++;
4444
}
45-
if (n.right != null) {
46-
q.add(n.right);
47-
next++;
45+
if (node.right != null) {
46+
queue.add(node.right);
47+
nextLevel++;
4848
}
49-
if (curr == 0) {
50-
levels.add(level);
49+
if (currentLevel == 0) {
50+
ret.add(level);
5151
level = new ArrayList<Integer>();
52-
curr = next;
53-
next = 0;
52+
currentLevel = nextLevel;
53+
nextLevel = 0;
5454
}
5555
}
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--;
5963
}
60-
return result;
64+
return ret;
6165
}
6266
}

ConvertSortedListtoBinarySearchTree.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
/**
32
* Given a singly linked list where elements are sorted in ascending order,
43
* convert it to a height balanced BST.

0 commit comments

Comments
 (0)