题目描述

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/

题解

层序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
if (!root) return {};
vector<int> res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front(); q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
res.push_back(node->val);
}
return res;
}
};

时间复杂度 O(n),空间复杂度 O(n)