1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { queue<TreeNode*> q; vector<vector<int>> ans;
if (root != nullptr) q.push(root); while (!q.empty()) { vector<int> sub; int qsz = q.size(); while (qsz--) { TreeNode* temp = q.front(); q.pop(); sub.push_back(temp->val); if (temp->left != nullptr) q.push(temp->left); if (temp->right != nullptr) q.push(temp->right); } ans.push_back(sub); }
return ans; } };
|