102. 二叉树的层序遍历

Introduction

Question:102. 二叉树的层序遍历

Analysis

比较简单,直接用队列做广度优先遍历就好了。

Implement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (root==nullptr) return res;
queue<TreeNode *> q;
q.push(root);
while(!q.empty()) {
vector<int> vec;
for(int i = 0, size = q.size(); i < size; i++) {
root = q.front(); q.pop();
vec.push_back(root->val);
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
res.push_back(vec);
}
return res;
}