-
Notifications
You must be signed in to change notification settings - Fork 2
/
zad2_ms.cpp
115 lines (106 loc) · 2.78 KB
/
zad2_ms.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
108
109
110
111
112
113
114
115
#define GO_LEFT -1
#define GO_RIGHT 0
#define SUMMARY 1
#include <algorithm>
#include <iostream>
#include <stack>
using namespace std;
typedef struct node *bin_tree;
struct node
{
int val;
bin_tree left, right;
};
typedef struct q *interesant;
struct q
{
bin_tree parent;
int *height;
int status;
};
bin_tree new_node(int val)
{
bin_tree node = (bin_tree)malloc((sizeof(int) + 2 * sizeof(bin_tree)));
node->val = val;
return node;
}
interesant create_interesant(bin_tree parent)
{
interesant inter = (interesant)malloc(2 * (sizeof(int) + sizeof(bin_tree)));
inter->parent = parent;
inter->height = (int *)malloc((size_t)2 * sizeof(int));
inter->status = GO_LEFT;
return inter;
}
// we can't go with recursion, so i made pseudo recursion
bool avl(bin_tree t)
{
int height = 0;
stack<interesant> pseudo;
pseudo.push(create_interesant(t));
while (1)
{
interesant current = pseudo.top();
switch (current->status)
{
case GO_LEFT:
// measure left subtree
if (current->parent->left == NULL)
{
current->height[0] = 0;
current->status = GO_RIGHT;
}
else
{
current->status = GO_RIGHT;
pseudo.push(create_interesant(current->parent->left));
}
break;
case GO_RIGHT:
// measure right subtree
if (current->parent->right == NULL)
{
current->height[1] = 0;
current->status = SUMMARY;
}
else
{
current->status = SUMMARY;
pseudo.push(create_interesant(current->parent->right));
}
break;
case SUMMARY:
// summary subtress heigh at pass own height to parent
// if this subtree is AVL
if (abs(current->height[0] - current->height[1]) > 1)
return false;
pseudo.pop();
if (pseudo.empty())
{
return true;
}
int height = max(current->height[0], current->height[1]) + 1;
if (pseudo.top()->parent->left == current->parent)
{
// current tree is a left subtree of a parent
pseudo.top()->height[0] = height;
}
else
{
// current tree is a right subtree of a parent
pseudo.top()->height[1] = height;
}
break;
}
}
return false;
}
int main()
{
bin_tree t = new_node(10);
t->left = new_node(5);
t->left->right = new_node(15);
// t->left->right->right = new_node(15);
t->right = new_node(14);
cout << avl(t) << endl;
}