jayati

Binary Tree Level Order Traversal

Mar 19th, 2023
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<int>> levelOrder(TreeNode* root) {
  4.         if(root == NULL)return {};
  5.         vector<vector<int>> ans;
  6.         vector<int> v;
  7.         int n;
  8.         queue<TreeNode*> q;
  9.         TreeNode* p;
  10.         q.push(root);
  11.         while(!q.empty()){
  12.             n = q.size();
  13.             v.clear();
  14.             while(n--){
  15.                 p = q.front();
  16.                 q.pop();
  17.                 v.push_back(p->val);
  18.                 if(p->left){
  19.                     q.push(p->left);
  20.                 }if(p->right){
  21.                     q.push(p->right);
  22.                 }
  23.             }
  24.             ans.push_back(v);
  25.         }
  26.         return ans;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment