题目:
题解:
/**
* 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;
if(nullptr==root)return result;
queue<TreeNode *> qt;
qt.push(root);
while(!qt.empty())
{
vector<int> temp;
int qLen=qt.size();//每一层节点个数
for(int i=0;i<qLen;++i)//当前层的所有节点出队列,节点值存储在临时数组中,下一层的所有节点全部进队列中
{
TreeNode* node=qt.front();qt.pop();
temp.push_back(node->val);
//单个节点的左右节点进队列
if(node->left)qt.push(node->left);
if(node->right)qt.push(node->right);
}
result.push_back(temp);//当前层的节点存储在二维数组中
}
return result;//返回二维数组
}
};