Two C++ Solutions, both not recursive


  • 0
    K

    solution:

        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> res;
            if(!root) return res;
            queue<TreeNode*> q;
            q.push(root);
            while(!q.empty()) {
                vector<int> temp;
                for(int i = 0, n = q.size(); i < n; i++) {
                    TreeNode* node = q.front();
                    q.pop();
                    temp.push_back(node->val);
                    if(node->left) q.push(node->left);
                    if(node->right) q.push(node->right);
                }
                res.push_back(temp);
            }
            return res;
        }
    

    solution1:

        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> res;
            if(!root) return res;
            queue<pair<TreeNode* , int>> q;
            q.push(make_pair(root, 0));
            while(!q.empty()) {
                TreeNode* node = q.front().first;
                int level = q.front().second;
                q.pop();
                if(level == res.size()) res.push_back( vector<int>() );
                res[level].push_back(node->val);
                if(node->left) q.push(make_pair(node->left, level + 1));
                if(node->right) q.push(make_pair(node->right, level + 1));
                
            }
            return res;
        }
    

Log in to reply
 

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