Typical BFS probelm, note that we need to save the size of the current queue and then use a for loop to save the result level by level.
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if (root == null) return ret;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
ArrayList<Integer> level = new ArrayList<>();
for (int i=0; i<size; i++) {
TreeNode tmp = queue.poll();
level.add(tmp.val);
if (tmp.left != null)
queue.offer(tmp.left);
if (tmp.right != null)
queue.offer(tmp.right);
}
ret.add(level);
}
return ret;
}
}
class Solution:
"""
@param root: A Tree
@return: Level order a list of lists of integer
"""
def levelOrder(self, root):
# write your code here
if not root:
return []
res = []
queue = collections.deque()
queue.append(root)
while queue:
curr_lvl, nodes = [], []
# Go through the nodes at current level
for i in range(len(queue)):
node = queue.popleft()
curr_lvl.append(node.val)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
res.append(curr_lvl)
return res