题目描述:
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] ]解题思路:二叉树的层次遍历,使用两个队列,一个队列保存层次遍历的结点,另一个保存层次遍历对应结点的深度,把相同深度的结点的值放到一个数组中。
AC代码如下:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (root == NULL) return ans;
queue<TreeNode*> nodes;
queue<int> levels;
nodes.push(root);
levels.push(1);
vector<int> values;
int cur_level = 1;
while (!nodes.empty()){
TreeNode* node = nodes.front();
nodes.pop();
int level = levels.front();
levels.pop();
if (level == cur_level){
values.push_back(node->val);
}
else{
ans.push_back(values);
values.clear();
values.push_back(node->val);
cur_level = level;
}
if (node->left != NULL){
nodes.push(node->left);
levels.push(level + 1);
}
if (node->right != NULL){
nodes.push(node->right);
levels.push(level + 1);
}
}
if (values.size()>0) ans.push_back(values);
return ans;
}
};