c++ solution


  • 0
    B
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            queue<TreeNode *> nodes;
            vector<vector<int>> result;
            if(!root) return result;
            
            int i=0;
            nodes.push(root);
            while(!nodes.empty()){
                result.push_back(vector<int> ());
                queue<TreeNode *> temp;
                
                while(!nodes.empty()){
                    TreeNode *n=nodes.front();
                    nodes.pop();
                    result[i].push_back(n->val);
                    if(n->left) temp.push(n->left);
                    if(n->right) temp.push(n->right);
                }
                i++;
                nodes=temp;
            }
            
            return result;
        }
    };
    

Log in to reply
 

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