-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounting Nodes in a BST.cpp
86 lines (83 loc) · 1.67 KB
/
Counting Nodes in a BST.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
#include <iostream>
struct node
{
int date;
node *l, *r;
};
int max = 0;
int sum1 = 0, sum2 = 0;
int order(node *root, int deep)
{
if (deep > max)
{
max = deep;
}
if (root->l != NULL)
order(root->l, deep + 1);
if (root->r != NULL)
order(root->r, deep + 1);
return 0;
}
int preorder(node *root, int deep)
{
if (deep == max)
sum1++;
if (deep == max - 1)
sum2++;
if (root->l != NULL)
preorder(root->l, deep + 1);
if (root->r != NULL)
preorder(root->r, deep + 1);
return 0;
}
int main()
{
int n;
std::cin >> n;
int x;
std::cin >> x;
node *root = new node;
root->date = x;
root->l = NULL;
root->r = NULL;
node *p = new node;
for (int i = 1; i < n; i++)
{
int y;
std::cin >> y;
p = root;
while (p != NULL)
{
if (y <= p->date && p->l != NULL)
{
p = p->l;
}
else if (y <= p->date && p->l == NULL)
{
node *q = new node;
q->date = y;
p->l = q;
q->l = NULL;
q->r = NULL;
break;
}
else if (y > p->date && p->r != NULL)
{
p = p->r;
}
else
{
node *q = new node;
q->date = y;
p->r = q;
q->l = NULL;
q->r = NULL;
break;
}
}
}
order(root, 0);
preorder(root, 0);
std::cout << sum1 << " + " << sum2 << " = " << sum1 + sum2;
return 0;
}