aboutsummaryrefslogtreecommitdiff
path: root/binary_tree_zigzag.cpp
blob: 186a99f7d69e80644a0dad38bdaf10b2be117487 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 103. Binary Tree Zigzag Level Order Traversal
#include "leetcode.h"
// given the 'root' of a binary tree, return the zigzag level order traversal of
// its nodes' values (ie. from left to right, then right to left for the next
// level)

class Solution {
public:
  vvd zigzagLevelOrder(TreeNode *root) {
    if (!root)
      return {};
    queue<TreeNode *> q;
    vvd ans;
    q.push(root);
    int level = 0;
    while (!q.empty()) {
      int sz = q.size();
      vector<int> curr(sz);
      for (int i = 0; i < sz; i++) {
        TreeNode *tmp = q.front();
        q.pop();
        if (level == 0)
          curr[i] = tmp->val;
        else
          curr[sz - i - 1] = tmp->val;
        if (tmp->left)
          q.push(tmp->left);
        if (tmp->right)
          q.push(tmp->right);
      }
      ans.push_back(curr);
      level = !level;
    }
    return ans;
  }
};