leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

trav.cpp (1297B)


      1 // runtime: beats 100%
      2 // memory: beats 62.88%
      3 
      4 
      5 /**
      6  * Definition for a binary tree node.
      7  * struct TreeNode {
      8  *     int val;
      9  *     TreeNode *left;
     10  *     TreeNode *right;
     11  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     12  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     13  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     14  * };
     15  */
     16 class Solution {
     17 public:
     18     vector<vector<int>> levelOrder(TreeNode* root) {
     19         vector<TreeNode*> nodes;
     20         vector<vector<int>> retLs;
     21 
     22         if(root != nullptr){
     23             nodes.push_back(root);
     24         }
     25 
     26         int itr = 0;
     27         while(!nodes.empty()){
     28             vector<int> ls;
     29             retLs.push_back(ls);
     30             int count = nodes.size();
     31 
     32             for(int i = 0; i < count; ++i){
     33                 TreeNode* current = nodes[0];
     34                 nodes.erase(nodes.begin());
     35                 retLs[itr].push_back(current->val);
     36                 
     37                 if(current->left != nullptr){
     38                     nodes.push_back(current->left);
     39                 }
     40 
     41                 if(current->right != nullptr){
     42                     nodes.push_back(current->right);
     43                 }
     44             }
     45 
     46             itr += 1;
     47         }
     48 
     49         return retLs;
     50     }
     51 };