Question
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,#,#,15,7},
3
/ 9 20
/ 15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Solution
/**
* 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>> out_vec;
vector<int> vec;
if(root == NULL)
return out_vec;
queue<TreeNode*> que;
que.push(root);
int level = 0;
int num = 1;
while(!que.empty())
{
vec.clear();
level = 0;
for(int i = 0; i < num; i ++)
{
root = que.front();
que.pop();
vec.push_back(root->val);
if(root->left != NULL)
{
que.push(root->left);
level ++;
}
if(root->right != NULL)
{
que.push(root->right);
level ++;
}
}
num = level;
out_vec.push_back(vec);
}
return out_vec;
}
};
时间: 2024-10-28 02:35:14