C++ solution with a list


  • 0
    Z
    /**
     * level traverse 
     * count the node in every level
     */
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            list<TreeNode*>li;
            vector<vector<int> >re;
            if(root != NULL)li.push_back(root);
            while(!li.empty()){
                int size = li.size();    //the size of current level 
                vector<int> vi;
                while(size  > 0){        // traverse current level
                    TreeNode* t = li.front();
                    li.pop_front();vi.push_back(t -> val);size--;
                    if(t -> left != NULL )li.push_back(t -> left);
                    if(t -> right != NULL )li.push_back(t -> right);
                }
                re.push_back(vi);       // load
            }
            return re;
        }
    };
    

Log in to reply
 

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