My C++ answer using Queue


  • 0
    F

    class Solution {
    public:
    vector<vector<int>> levelOrder(TreeNode* root){
    vector<vector<int>> layers;
    deque<TreeNode*> d;
    if(root == NULL) return layers;
    d.push_back(root);

        int levelt = 0;
        int leveln = 0;
        int i = 0;
    
        cout<<"here we are"<<endl;
    
        vector<int> temp;
    
        while(!d.empty()){
            i++;
            temp.push_back(d.front()->val);
            if(d.front()->left != NULL){
                d.push_back(d.front()->left);
                leveln++;
            }
            if(d.front()->right != NULL){
                d.push_back(d.front()->right);
                leveln++;
            }
            if(i >= levelt){
                layers.push_back(temp);
                temp.clear();
                levelt = leveln;
                leveln = 0;
                i = 0;
            }
            d.pop_front();
        }
    
        vector<vector<int>> relayers;
        for(vector<vector<int>>::reverse_iterator it = layers.rbegin(); it != layers.rend(); it++){
            relayers.push_back(*it);
        }
        return relayers;
    }
    

    };


Log in to reply
 

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