Consice recursive C++ solution


  • 3
    E

    The idea is to solve the problem normally if it was about traversing every level separately then reverse odd rows.

    class Solution {
    public:
        void build(TreeNode* n, vector<vector<int>>& R, int d) {
            if (!n) return;
            if (d == R.size()) R.push_back(vector<int>());
            R[d].push_back(n->val);
            build(n->left, R, d + 1);
            build(n->right, R, d + 1);
        }
        
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> R;
            build(root, R, 0);
            for (int i = 1; i < R.size(); i += 2) reverse(R[i].begin(), R[i].end());
            return R;
        }
    };

Log in to reply
 

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