Speed : 25.35%
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null) return result;
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.add(root);
TreeNode curr = null;
while (!que.isEmpty()) {
List<Integer> subResult = new ArrayList<Integer>();
int size = que.size();
for (int i = 0; i < size; i++) {
curr = que.poll();
subResult.add(curr.val);
if (curr.left != null) que.add(curr.left);
if (curr.right != null) que.add(curr.right);
}
result.add(0, subResult);
}
return result;
}
}
Version #1 二刷
机智如我用了LinkedList作为level的structure
快了好多666
Runtime: 1 ms, faster than 84.86% of Java online submissions for Binary Tree Level Order Traversal II.
Memory Usage: 38.9 MB, less than 95.24% of Java online submissions for Binary Tree Level Order Traversal II.
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
if (root == null) {
return res;
}
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
while (!que.isEmpty()) {
int size = que.size();
List<Integer> level = new ArrayList<>();
while (size-- > 0) {
TreeNode curr = que.poll();
level.add(curr.val);
if (curr.left != null) {
que.offer(curr.left);
}
if (curr.right != null) {
que.offer(curr.right);
}
}
res.add(0, level);
}
return res;
}
}
Version #2 Collections.reverse(result);
Speed : 73.26%
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) return result;
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.add(root);
TreeNode curr = null;
int size = 0;
while (!que.isEmpty()) {
List<Integer> subResult = new ArrayList<Integer>();
size = que.size();
for (int i = 0; i < size; i++) {
curr = que.poll();
subResult.add(curr.val);
if (curr.left != null) que.add(curr.left);
if (curr.right != null) que.add(curr.right);
}
result.add(subResult);
//subResult.clear();
}
Collections.reverse(result);
return result;
}
}
No comments:
Post a Comment