It is my AC solution.


  • 10
    D

    Here i use bfs with queue. The type of queue is pair where the first argument is tree node and second is level number. Can I or is it right to use pair here ?

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

Log in to reply
 

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