-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeZigzagLevelOrderTraversal.cc
More file actions
61 lines (56 loc) · 1.39 KB
/
Copy pathBinaryTreeZigzagLevelOrderTraversal.cc
File metadata and controls
61 lines (56 loc) · 1.39 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <sstream>
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > result;
if (root == NULL) return result;
stack<TreeNode *> stk1, *curstk;
stack<TreeNode *> stk2, *nextstk, *tmp;
stk1.push(root);
curstk = &stk1;
nextstk = &stk2;
bool flag = false;
vector<int> data(0);
while (!curstk->empty()) {
data.clear();
while (!curstk->empty()) {
root = curstk->top();
curstk->pop();
data.push_back(root->val);
if (flag) {
if (root->right != NULL) nextstk->push(root->right);
if (root->left != NULL) nextstk->push(root->left);
} else {
if (root->left != NULL) nextstk->push(root->left);
if (root->right != NULL) nextstk->push(root->right);
}
}
result.push_back(data);
flag = !flag;
tmp = curstk;
curstk = nextstk;
nextstk = tmp;
}
return result;
}
};
int main(int argc, char const *argv[]) {
/* code */
return 0;
}