-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree_zigzag_level_order_traversal.cpp
107 lines (88 loc) · 2.34 KB
/
binary_tree_zigzag_level_order_traversal.cpp
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
// Date: Nov 10, 2014
#include <iostream>
#include <stack>
#include <utility>
#include <vector>
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)
{
vector<vector<int> > vec;
if (root == NULL)
{
return vec;
}
stack<TreeNode*> stk1, stk2;
// push children in the order (left,right) in one stack and reverse in another stack
int level;
stk1.push(root);
while (!stk1.empty())
{
level = vec.size();
vec.push_back(vector<int>());
while(!stk1.empty())
{
TreeNode* node = stk1.top();
stk1.pop();
vec[level].push_back(node->val);
if (node->left)
{
stk2.push(node->left);
}
if (node->right)
{
stk2.push(node->right);
}
}
if (!stk2.empty())
{
level = vec.size();
vec.push_back(vector<int>());
while (!stk2.empty())
{
TreeNode* node = stk2.top();
stk2.pop();
vec[level].push_back(node->val);
if (node->right)
{
stk1.push(node->right);
}
if (node->left)
{
stk1.push(node->left);
}
}
}
}
return vec;
}
};
TreeNode* create_binary_tree()
{
TreeNode* root = new TreeNode(3);
TreeNode* node = new TreeNode(9);
root->left = node;
node = new TreeNode(20);
root->right = node;
TreeNode* leftNode = new TreeNode(15);
TreeNode* rightNode = new TreeNode(7);
node->left = leftNode;
node->right = rightNode;
return root;
}
int main(int argc, char* argv[])
{
TreeNode* root = create_binary_tree();
Solution sln;
vector<vector<int> > vec = sln.zigzagLevelOrder(root);
return 0;
}