c++ iterative simple solution with queue


  • 0
    A
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        struct N {
         TreeNode* p;
         int lev;
         N(TreeNode* pp, int ll):p(pp),lev(ll){}
        };
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int> > a;
            queue<N> q;
            if (root == NULL) return a;
            q.push({root, 1});
            while(q.size()) {
                if ((q.front()).lev != a.size()) a.push_back(vector<int>());
                a[a.size()-1].push_back(q.front().p->val);
                if (q.front().p->left) q.push({q.front().p->left, (q.front()).lev+1});
                if (q.front().p->right) q.push({q.front().p->right, (q.front()).lev+1});
                q.pop();
            }
            return a;
        }
    };
    

Log in to reply
 

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