-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathis_binary_tree_symmetrical.cpp
55 lines (47 loc) · 1.37 KB
/
is_binary_tree_symmetrical.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
#include "data_struct_types.h"
#include "print_utils.h"
#include <deque>
using namespace data_struct_types;
using namespace print_utils;
bool IsBinaryTreeSymmetrical(BinaryTreeNode<int> *root)
{
std::deque<BinaryTreeNode<int> *> level_queue;
std::deque<int> stack;
level_queue.push_front(root);
stack.push_front(root->data);
while (!level_queue.empty())
{
auto node = level_queue.back();
level_queue.pop_back();
if (!stack.empty() && node->data == stack.front())
{
stack.pop_front();
}
else
{
stack.push_front(node->data);
}
if (node->left != nullptr)
{
level_queue.push_front(node->left);
}
if (node->right != nullptr)
{
level_queue.push_front(node->right);
}
}
return stack.empty();
}
int main(int argc, char const *argv[])
{
BinaryTreeNode<int> *root = new BinaryTreeNode<int>(0);
root->left = new BinaryTreeNode<int>(1);
root->right = new BinaryTreeNode<int>(1);
root->left->left = new BinaryTreeNode<int>(3);
root->left->right = new BinaryTreeNode<int>(4);
root->right->left = new BinaryTreeNode<int>(4);
root->right->right = new BinaryTreeNode<int>(3);
bool symmetrical = IsBinaryTreeSymmetrical(root);
std::cout << symmetrical << std::endl;
return 0;
}