从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
示例:
二叉树:[3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回结果:
[
[3],
[20,9],
[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>> res;
if(root == NULL) return res;
queue<TreeNode*> q;
q.push(root);
int count = 0;
while(!q.empty()){
vector<int> temp;
int levelSize = q.size();
for(int i = 0 ; i < levelSize; i++){
TreeNode* cur = q.front();
q.pop();
temp.push_back(cur->val);
if(cur->left != NULL) q.push(cur->left);
if(cur->right != NULL) q.push(cur->right);
}
if(count % 2 == 1) reverse(temp.begin(), temp.end());
res.push_back(temp);
count++;
}
return res;
}
};