C++ 3ms concise recursive version

  • 0

    Use depth to track level for preOrder traversal.
    Even rows, push back, odd rows insert to front.

        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> res;
            helper(root, res, 0);
            return res;
        void helper(TreeNode* root, vector<vector<int>>& res, int depth) {
            if (!root) return;
            if (depth >= res.size()) res.resize(depth+1);
            if (depth%2==0)
                res[depth].insert(res[depth].begin(), root->val);
            helper(root->left, res, depth+1);
            helper(root->right, res, depth+1);

Log in to reply

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