题目:
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] ]
题目分析:
这道题目就是107题的简化版,省略了倒叙的步骤,具体的解法参见107分析。此处只挂代码嘻嘻嘻
代码:
/**
* 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>> res;
queue<TreeNode*> Q;
Q.push(root);
int th = 1;
int ne = 0;
if(root == NULL){
return res;
}
while(!Q.empty()){
vector<int> put;
for(int i = 0; i< th; i++){
TreeNode* node = Q.front();
put.push_back(node->val);
if(node->left != NULL){
Q.push(node->left);
ne++;
}
if(node->right != NULL){
Q.push(node->right);
ne++;
}
Q.pop();
}
res.push_back(put);
th = ne;
ne = 0;
}
return res;
}
};