Binary tree level-order traversal

LeetCode problem 102. Binary Tree Level Order Traversal.

## Problem description

Given a binary tree, return the *level order* traversal of its nodes' values. (ie, from left to right, level by level).

For example:

Given binary tree `[3,9,20,null,null,15,7]`,

```
     3
    / \
   9  20
     /  \
    15   7

```

Return its level order traversal as:

```
 [
   [3],
   [9,20],
   [15,7]
 ]

```

## Analysis

We can use breadth-first search to do this problem, by maintaining a **BFS queue**.

We can maintain an array to produce the output. Each element of this array is also an array that contains the nodes of the same level.

When we process each level of nodes:

1. Record the number of nodes in the current level.
2. Pop each node from current level one by one from the BFS queue, and add the popped nodes to the same-level array. At the same time, add all children of nodes of current level to the BFS queue.
3. After processing each level, add the same-level array to the output array.

Repeat until the BFS queue is empty, i.e. all nodes are processed.

### Example

Input:

```
           1
          / \
        2     3
       / \   / \
      4   5 6   7

```

Iterations of the BFS process
 2
 3
* 2, 3
* **4, 5, 6, 7**

Output:

```
[
  [1],
  [2, 3],
  [4, 5, 6, 7],
]

```

### Complexity analysis

#### Time complexity

Since each node is traversed once, the time complexity is **O(n)**.

#### Space complexity

Stack
The space complexity on stack is O(1) because there is no recursion involved.
Heap
We used a BFS queue. The worst case is a **perfect binary tree**: layer 1 has 1 node, layer 2 has 2 nodes, layer 3 has 4 nodes, layer 4 has 8 nodes, …, and layer *k* has

2

k
−
1

{\displaystyle 2^{k-1}}

 nodes. In other words, the maximum number of elements in the queue is one half of the total number of nodes in the tree.
So the space complexity on heap is O(n).
The total space complexity is **O(n)**.

## Solution

### C++

```
/\*\*
 \* Definition for a binary tree node.
 \* struct TreeNode {
 \* int val;
 \* TreeNode \*left;
 \* TreeNode \*right;
 \* TreeNode() : val(0), left(nullptr), right(nullptr) {}
 \* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 \* TreeNode(int x, TreeNode \*left, TreeNode \*right) : val(x), left(left), right(right) {}
 \* };
 \*/
class Solution {
public:
 std::vector<std::vector<int>> levelOrder(TreeNode\* root) {
 std::vector<std::vector<int>> output;

 if (root == nullptr) {
 return output;
 }

 // use BFS
 // put each level of nodes into one vector
 std::queue<TreeNode\*> BFSQueue;
 BFSQueue.push(root);
 while (!BFSQueue.empty()) {
 int numCurrLevelNodes = BFSQueue.size();
 std::vector<int> currLevelNodes;
 for (int i = 0; i < numCurrLevelNodes; ++i) {
 // add each node of current level to output
 TreeNode\* curr = BFSQueue.front();
 BFSQueue.pop();
 currLevelNodes.push\_back(curr->val);

 // add children of curr to BFSQueue
 if (curr->left != nullptr) {
 BFSQueue.push(curr->left);
 }
 if (curr->right != nullptr) {
 BFSQueue.push(curr->right);
 }
 }
 output.push\_back(currLevelNodes);
 }

 return output;
 }
};

```

### Java

```
/\*\*
 \* Definition for a binary tree node.
 \* public class TreeNode {
 \* int val;
 \* TreeNode left;
 \* TreeNode right;
 \* TreeNode() {}
 \* TreeNode(int val) { this.val = val; }
 \* TreeNode(int val, TreeNode left, TreeNode right) {
 \* this.val = val;
 \* this.left = left;
 \* this.right = right;
 \* }
 \* }
 \*/
class Solution {
 public List<List<Integer>> levelOrder(TreeNode root) {
 List<List<Integer>> output = new ArrayList<>();

 if (root == null) {
 return output;
 }

 // use BFS
 // put each level of nodes into one vector
 Queue<TreeNode> BFSQueue = new ArrayDeque<>();
 BFSQueue.offer(root);
 while (!BFSQueue.isEmpty()) {
 int numCurrLevelNodes = BFSQueue.size();
 ArrayList<Integer> currLevelNodes = new ArrayList<>();
 for (int i = 0; i < numCurrLevelNodes; ++i) {
 // add each node of current level to output
 TreeNode curr = BFSQueue.poll();
 currLevelNodes.add(curr.val);

 // add children of curr to BFSQueue
 if (curr.left != null) {
 BFSQueue.offer(curr.left);
 }
 if (curr.right != null) {
 BFSQueue.offer(curr.right);
 }
 }
 output.add(currLevelNodes);
 }

 return output;
 }
}

```

## See also

* Binary tree traversal
	+ Binary tree pre-order traversal
	+ Binary tree in-order traversal
	+ Binary tree post-order traversal
* Check completeness of a binary tree