C++ solution(queue and a for loop 3ms)


  • 0
    S

    Using a loop to traverse current elements which are at a same level.

    vector<vector<int>> levelOrder(TreeNode* root){
    
      vector<vector<int>> res;
      if(!root) return res;
    
      queue<TreeNode*> que;
      que.push(root);
    
      while(!que.empty()){
    
        int cur_size = que.size();
        vector<int> vec;
        for(int i=0;i<cur_size;i++){
          TreeNode* tmp = que.front();
          vec.push_back(tmp->val);
          que.pop();
          if(tmp->left) que.push(tmp->left);
          if(tmp->right) que.push(tmp->right);
        }
        res.push_back(vec);
      }
      return res;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.