剑指 Offer 32 - II. 从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树:[3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回:
[
[3],
[9,20],
[15,7]
]
限制:
节点总数 <= 1000
思路:BFS |
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> q;
if(!root) return {};
q.push(root);
while(q.size()){
auto n = q.size();
vector<int> v;
while(n--){
auto t = q.front(); q.pop();
v.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
ans.push_back(v);
}
return ans;
}
};