Thought:
Basically the same with prior problem, the only change is dealing with the result.
Code:
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
int depth = 0;
Queue<TreeNode> q1 = new LinkedList<TreeNode>();
Queue<Integer> q2 = new LinkedList<Integer>();
if(root == null) return result;
q1.offer(root);
q2.offer(depth + 1);
while(q1.peek() != null){
TreeNode element = q1.poll();
depth = q2.poll();
if(result.size() < depth){
result.add(0, new ArrayList<Integer>());
}
result.get(0).add(element.val);
if(element.left != null){
q1.offer(element.left);
q2.offer(depth + 1);
}
if(element.right != null){
q1.offer(element.right);
q2.offer(depth + 1);
}
}
return result;
}
}
No comments:
Post a Comment