Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- vector<vector<int>> levelOrder(TreeNode* root) {
- vector<vector<int>> ans;
- if(!root) return ans;
- queue<TreeNode*> q;
- q.push(root);
- while(!q.empty()){
- vector<int> level;
- int sz = q.size();
- for(int i=0; i<sz; i++){
- auto p = q.front();
- q.pop();
- level.push_back(p->val);
- if(p->left) q.push(p->left);
- if(p->right) q.push(p->right);
- }
- ans.push_back(level);
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment