How could this code without return statement get AC?


  • 0
    T

    class Solution {

    public:
    vector<vector<int> > levelOrderBottom(TreeNode *root) {

    vector<vector<int> > result;
    vector<int> tmp;
    
    if(root == NULL)
      return result;
    
    queue<TreeNode *> myQueue;
    myQueue.push(root);
    
    int count = 1;
    int count_next = 0;
    
    while(!myQueue.empty()) {
      TreeNode *node = myQueue.front();
      myQueue.pop();
      tmp.push_back(node->val);
      count--;
      if(node->left != NULL) {
        myQueue.push(node->left);
        count_next++;
      } 
    
      if(node->right != NULL) {
        myQueue.push(node->right);
        count_next++;
      }
    
      if(count == 0) {
        result.push_back(tmp);
        tmp.clear();
        count = count_next;
        count_next = 0;
      }
    }
    
    std::reverse(result.begin(),result.end());
    //return result;
    

    }

    };


  • 0
    T

    And this similar code will FAIL.

    class Solution {
    public:
    vector<vector<int> > levelOrderBottom(TreeNode *root) {

    vector<vector<int> > result;
    vector<int> tmp;
    
    vector<vector<int> > empty_result;
    if(root == NULL)
      return empty_result;
    
    queue<TreeNode *> myQueue;
    myQueue.push(root);
    
    int count = 1;
    int count_next = 0;
    
    while(!myQueue.empty()) {
      TreeNode *node = myQueue.front();
      myQueue.pop();
      tmp.push_back(node->val);
      count--;
      if(node->left != NULL) {
        myQueue.push(node->left);
        count_next++;
      } 
    
      if(node->right != NULL) {
        myQueue.push(node->right);
        count_next++;
      }
    
      if(count == 0) {
        result.push_back(tmp);
        tmp.clear();
        count = count_next;
        count_next = 0;
      }
    }
    
    std::reverse(result.begin(),result.end());
    //return result;
    

    }

    };


Log in to reply
 

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