0429.cpp (569B)
1 class Solution { 2 public: 3 vector<vector<int>> levelOrder(Node *root) { 4 if (!root) return {}; 5 6 vector<vector<int>> res; 7 queue<Node *> q; 8 9 q.push(root); 10 for (int lvl = 0; !q.empty(); lvl++) { 11 res.push_back(vector<int>()); 12 for (int t = q.size(); t > 0; t--) { 13 Node *root = q.front(); 14 q.pop(); 15 res[lvl].push_back(root->val); 16 for (Node *c : root->children) 17 q.push(c); 18 } 19 } 20 return res; 21 } 22 };