102. Binary Tree Level Order Traversal

每日一题 2019 - 04 - 22

题目:

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

解法:

这个题让求出二叉树的层次遍历的序列,思路很直观,直接使用数据结构队列即可完成任务,但是这个题让不同层次之间的输出的序列处于不同的 vector 中,所以需要进行额外的处理:也即对每一行的输出加上 NULL ,每次遇到 NULL 就判断是否已经到末尾,即可完成任务;


代码:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 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) {
queue<TreeNode*> temp ;
vector<vector<int>> res ;
temp.push(root);
temp.push(NULL);
if(root == NULL)
{
return res ;
}
vector<int> cur ;
while( temp.size() != 0 )
{
TreeNode *now = temp.front();
temp.pop();
if(now == NULL)
{
res.push_back(cur);
cur.resize(0);
if( temp.size() > 0 )
{
temp.push(NULL);
}
}
else
{
cur.push_back(now->val);
if(now->left)
{
temp.push(now->left);
}
if(now->right)
{
temp.push(now->right);
}
}
}
return res ;
}
};
0%
undefined