102. Binary Tree Level Order Traversal
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] ]
解题思路:
采用双队列来处理。
用当前队列current来处理本层的所有节点,将本层信息记录在vector中。用next来记录下一层的节点信息。
当前队列处理后,将本层信息的vector存储到结果vector中。清空存储本层信息的vector。将current和next交换。然后重新处理current队列。
代码如下:
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
|
/**
* 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) {
vector<vector<
int
>> result;
queue<TreeNode *> current,next;
vector<
int
> level;
if
(NULL == root)
return
result;
current.push(root);
while
(current.size() > 0)
{
while
(current.size() > 0)
{
TreeNode *p = current.front();
current.pop();
level.push_back(p->val);
if
(p->left)
next.push(p->left);
if
(p->right)
next.push(p->right);
}
result.push_back(level);
level.clear();
current.swap(next);
}
return
result;
}
};
|
本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1834819