Sharing my 12ms C++ solution using queue


  • 1
    T
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
     
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> result;
            
            if(root == NULL)
                return result;
                
            queue<TreeNode*> myQueue;
            queue<int>       levels;
            
            myQueue.push(root);
            levels.push(0);
            
            TreeNode* tempNode;
            int       tempLevel;
            
            while(myQueue.size() > 0)
            {
                tempNode = myQueue.front();
                myQueue.pop();
                tempLevel = levels.front();
                levels.pop();
                
                if(tempLevel < result.size())
                    result[tempLevel].push_back(tempNode->val);
                else
                {
                    result.push_back(vector<int>(1, tempNode->val));
                }
                
                if(tempNode->left)
                {
                    myQueue.push(tempNode->left);
                    levels.push(tempLevel+1);
                }
                
                if(tempNode->right)
                {
                    myQueue.push(tempNode->right);
                    levels.push(tempLevel+1);
                }
      
            }
            
            return result;
        }
    };

  • 0
    L

    hi, i can't understand what "tempLevel " is used for?


Log in to reply
 

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