Problem
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]
,
1 |
|
return its level order traversal as:
1 |
|
Explanation 1
-
We can use the BFS method. We store each layer’s values into a list, then add this list into the result. The problem now of the BFS is we don’t know the number of elements in each layer. To solve this, we need to record the size of each layer before we pop and push the left child and right child elements into the list, and we pop the number of elements base on this size.
-
From the above example, we first push 3 into the queue, record the size is 1, then we pop 1 element adding to a list, then push its left and right child 9 and 20, now the queue has 2 elements, so we update the size to 2. Then we should pop 2 elements this time, we pop 9, pop 20, adding to a list, and push its left and right child 15 and 7. Now the queue has 2 elements, so we update its size to 2, and we only pop size=2 elements and adding to the list, etc, until the queue is empty.
Solution 1
1 |
|
Explanation 2
We can also use DFS method to solve this problem.
Solution 2
1 |
|