Short 8ms C++ solution with queue


  • 18
    D
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            if (!root) { return {}; }
            vector<int> row;
            vector<vector<int> > result;
            queue<TreeNode*> q;
            q.push(root);
            int count = 1;
    
                while (!q.empty()) {
                if (q.front()->left) { q.push(q.front()->left); }
                if (q.front()->right) { q.push(q.front()->right); }
                row.push_back(q.front()->val), q.pop();
                if (--count == 0) {
                    result.emplace_back(row), row.clear();
                    count = q.size();
                }
            }
            return result;
        }
    };

  • 23
    P
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        queue<TreeNode *> q;
        if (root) q.push(root);
        while (!q.empty()) {
            int len = q.size();
            vector<int> level;
            for (int i = 0;i < len;++i) {
                TreeNode *node = q.front();
                level.push_back(node->val);
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
                q.pop();
            }
            ans.push_back(level);
        }
        return ans;
    }

  • 2
    R

    similar solution using 2 loops

    vector<vector<int>> levelOrder(TreeNode* root) {
    	vector<vector<int>> res;
    	if(!root)
    		return res;
    	queue<TreeNode*> q;
    	q.push(root);
    	vector<int> v;
    	while(!q.empty()){
    		int n=q.size();
    		while(n>0){
    			auto node=q.front();
    			v.push_back(node->val);
    			if(node->left)
    				q.push(node->left);
    			if(node->right)
    				q.push(node->right);
    			q.pop();
    			--n;
    		}
    		res.emplace_back(v);
    		v.clear();
    	}
    	return res;
    }

  • 0
    J

    Nice solution


Log in to reply
 

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