思路
使用队列。每次遍历一层节点,在遍历前先获得每层节点的个数,对整层遍历,同时将不为空的左右子节点添加到队列中
代码如下:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root == NULL)
return res;
vector<int> level;
queue<TreeNode*> que;
que.push(root);
int levelSize = 0;
while(!que.empty()){
level.clear();
levelSize = que.size();
// 遍历完一层
for(int i = 1; i <= levelSize; i++){
// 左边
if(que.front()->left != NULL)
que.push(que.front()->left);
// 右边
if(que.front()->right != NULL)
que.push(que.front()->right);
level.push_back(que.front()->val);
que.pop();
}
res.push_back(level);
}
return res;
}
};