二叉树的层次遍历
遍历结果每一层用数组保存
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;
if(!root) return NULL;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
vector<int> temp;
int len=q.size();
for(int i=0;i!=len;i++)
{
TreeNode* t=q.front();
temp.push_back(t->val);
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
ans.push_back(temp);
}
return ans;
}
}