aboutsummaryrefslogtreecommitdiff
path: root/binary_tree_level_traverse.cpp
blob: 47a69da957ed9c374f1d0477adef99825e145f6d (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
#include "leetcode.h"

class Solution {
public:
  vector<vector<int>> levelOrder(TreeNode *root) {
    vector<vector<int>> ans;
    if (!root)
      return ans;
    queue<TreeNode *> q;
    q.push(root);
    q.push(NULL);
    vector<int> curr;
    while (!q.empty()) {
      TreeNode *t = q.front();
      q.pop();
      if (t == NULL) {
        ans.push_back(curr);
        curr.resize(0);
        if (q.size() > 0)
          q.push(NULL);
      } else {
        curr.push_back(t->val);
        if (t->left)
          q.push(t->left);
        if (t->right)
          q.push(t->right);
      }
    }
    return ans;
  }
};