-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree_zigzag_order_traversal.cpp
71 lines (64 loc) · 1.67 KB
/
binary_tree_zigzag_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
// =====================================================================================
//
// Filename: binary_tree_zigzag_order_traversal.cpp
//
// Description: 103. Binary Tree Zigzag Level Order Traversal.
//
// Version: 1.0
// Created: 08/09/2019 07:53:48 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <vector>
using std::vector;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution
{
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root)
{
vector<vector<int>> values;
zigzagLevelOrder(root, 0, &values);
return values;
}
private:
void zigzagLevelOrder(TreeNode* node, int height, vector<vector<int>>* values)
{
if (node == nullptr)
{
return;
}
if (values->size() == height)
{
values->push_back(vector<int>());
}
if ((height & 0x01) == 0)
{
values->at(height).push_back(node->val);
}
else
{
values->at(height).insert(values->at(height).begin(), node->val);
}
zigzagLevelOrder(node->left, height + 1, values);
zigzagLevelOrder(node->right, height + 1, values);
}
};
int main(int argc, char* argv[])
{
TreeNode* root = nullptr;
auto values = Solution().zigzagLevelOrder(root);
printf("Values's size %ld\n", values.size());
return 0;
}