102.cpp (517B)
1 class Solution { 2 public: 3 vector<vector<int>> levelOrder(TreeNode *root) { 4 if (!root) return {}; 5 6 vector<vector<int>> res; 7 queue<TreeNode *> 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 TreeNode *root = q.front(); 14 q.pop(); 15 res[lvl].push_back(root->val); 16 if (root->left) q.push(root->left); 17 if (root->right) q.push(root->right); 18 } 19 } 20 return res; 21 } 22 };