剑指 Offer 32 - I 从上到下打印二叉树
概述
https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
层序遍历
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
vector<int> ans;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
while (sz > 0) {
sz --;
auto n = q.front(); q.pop();
if (n) {
ans.push_back(n->val);
q.push(n->left);
q.push(n->right);
}
}
}
return ans;
}
};
Links: sword-offer-32-1