题目链接:剑指 Offer 32 - I. 从上到下打印二叉树
思路:层序遍历
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
vector<int> v;
if (root == nullptr) return v;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int current_level_size = q.size();
for (int i = 1; i <= current_level_size; i++) { //等号别忘记
auto node = q.front();
q.pop();
v.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return v;
}
};