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],

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

return its level order traversal as:

1
2
3
4
5
[
[3],
[9,20],
[15,7]
]

Solution:

This is a very basic problem, we can use dfs to solve this problem. One thing to notice is that we need to use a depth variable to store the level where we are.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
dfs(root, 0);
return res;
}

void dfs(TreeNode *root, int depth)
{
if(root == NULL) return;
if(res.size() == depth) //need to insert a new layer
res.push_back(vector<int>());

res[depth].push_back(root->val);
dfs(root->left, depth + 1);
dfs(root->right, depth + 1);
}
private:
vector<vector<int>> res;

};

time complexity: O(n)

Second time:

Use BFS to do traversal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if(!root) return vector<vector<int>>{};
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
res.push_back(vector<int>{});
int size= q.size();
for(int i= 0; i< size; i++){
TreeNode* tmp= q.front(); q.pop();
res[res.size()-1].push_back(tmp->val);
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
}
return res;
}
};

time complexity: $O(n)$
space complexity: $O(n)$