We use two Queue, one stores the TreeNode, one stores their corresponding depth.
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(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(new ArrayList<Integer>());
}
result.get(depth - 1).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