# LeetCode-Binary Tree Level Order Traversal-解题报告

111人阅读 评论(0)

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


/**
* 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> >ans;
queue<TreeNode*>Q;
vector<int>tmp;
if (root == NULL)return ans;
Q.push(root);
while (!Q.empty())
{
tmp.clear();
int size = Q.size();
for (int i = 0; i < size; ++i)
{
TreeNode* t = Q.front();
Q.pop();
tmp.push_back(t->val);
if (t->left != NULL)Q.push(t->left);
if (t->right != NULL)Q.push(t->right);
}
ans.push_back(tmp);
}
return ans;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：15527次
• 积分：850
• 等级：
• 排名：千里之外
• 原创：72篇
• 转载：6篇
• 译文：0篇
• 评论：0条
文章分类