C++ Layer travesal without using queue

  • 0

    In standard layer traversal technique, we cannot differentiate whether the element in queue has moved to the next layer.
    To address this issue we use two vectors instead, one for node in current layer, and put there children (nodes of next layer) in the other vector. They are swapped after a layer has been traversed.

    class Solution {
        vector<int> largestValues(TreeNode* root) {
            vector<int> result;
            if (root==NULL) return result;
            vector<TreeNode*> cur;
            vector<TreeNode*> next;
            while (!cur.empty()) {
                int m = INT_MIN;
                for (auto p : cur) {
                    m = max(m, p->val);
                    if (p->left) next.push_back(p->left);
                    if (p->right) next.push_back(p->right);                
                swap(cur, next);
            return result;

Log in to reply

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