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