Simple iterative solution.


  • 0
    S

    class Solution {
    public:

    vector<vector<int>> levelOrder(TreeNode* root) {
        
        std::queue<TreeNode*> q;
        TreeNode* x;
        std::vector<int> temp;
        std::vector<vector<int>> result;
        if(root==NULL)
            return result;
        q.push(root);
        while(q.size()){
            temp.clear();
            int siz=q.size();
            for(int i=0;i<siz;i++){
                if((q.front())->left)
                {
                    q.push((q.front())->left);
                }
                if((q.front())->right)
                {
                    q.push((q.front())->right);
                }
                temp.push_back((q.front())->val);
                q.pop();
            }
            result.push_back(temp);
            
        }
        return result;
    }
    

    };


Log in to reply
 

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