从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回其层次遍历结果:
[
[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;
vector<int> tmp;
queue<TreeNode*> qe;
if(root == NULL)
return ans;
qe.push(root);
tmp.push_back(root->val);
ans.push_back(tmp);
tmp.clear();
TreeNode* cur;
TreeNode* ptr = qe.front();
while(!qe.empty())
{
cur = qe.front();
if(cur->left != NULL)
{
qe.push(cur->left);
tmp.push_back(cur->left->val);
}
if(cur->right != NULL)
{
qe.push(cur->right);
tmp.push_back(cur->right->val);
}
if(ptr == cur)
{
ptr = qe.back();
if(!tmp.empty())
ans.push_back(tmp);
tmp.clear();
}
qe.pop();
}
return ans;
}
};