Binary Tree Level Order Traversal
Code link:
Idea
We can do a BSF against the tree with a queue. The key here is to ensure all the nodes within the same level are added to the same list.
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> results = new ArrayList<>();
if (root == null) {
return results;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> numsInLevel = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode current = queue.poll();
numsInLevel.add(current.val);
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}
results.add(numsInLevel);
}
return results;
}
}
- Time: O(n) as we have to process each node once.
- Space: O(n).
浙公网安备 33010602011771号