二叉树层序遍历模板

迭代写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode*> que;
if (root != NULL) que.push(root);
while (!que.empty()) {
int size = que.size();
vector<int> vec;
// 这里一定要使用固定大小size,不要使用que.size(),因为que.size()是不断变化的
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
vec.push_back(node->val);
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}

递归写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void order(TreeNode* cur, vector<vector<int>>& result, int depth) {
if (cur == NULL) return;

if (result.size() == depth) result.push_back(vector<int>());

result[depth].push_back(cur->val);
order(cur->left, result, depth + 1);
order(cur->right, result, depth + 1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
int depth = 0;
order(root, result, depth);
return res;
}

https://leetcode.cn/problems/binary-tree-level-order-traversal/

https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/