Simple and easy understand C++ solution


  • 0
    S
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
          vector<vector<int>> ret;
          levelRecursion(root, ret, 0);
          return ret;
    }
        
    void levelRecursion(TreeNode* root, vector<vector<int>> &ret, int level) {
          if (!root) return;
          if (level == ret.size()) ret.push_back(vector<int>());
          if (level % 2) {
                ret[level].insert(ret[level].begin(), root->val);
          } else {
                ret[level].push_back(root->val);
          }
          levelRecursion(root->left, ret, level + 1);
          levelRecursion(root->right, ret, level + 1);
    }
    

Log in to reply
 

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