-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZOJ-1700-Falling Leaves-binary search tree.cpp
101 lines (92 loc) · 1.92 KB
/
ZOJ-1700-Falling Leaves-binary search tree.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
#include <iostream>
#include <stack>
#include<stdlib.h>
#include<stdio.h>
#include <string>
#include <algorithm>
using namespace std;
typedef struct node
{
char data;
struct node* right;
struct node* left;
} node;
void insert(node** tree, char val)
{
node *temp = NULL;
if(!(*tree)) // node is empty
{
temp = (node*)malloc(sizeof(node)); // allocate the space of a node
temp->left = temp->right = NULL;
temp->data = val;
*tree = temp;
return;
}
if(val < (*tree)->data)
{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val);
}
}
void construct(node **tree, string str, int n)
{
for(int i = 0; i < n; i++)
{
insert(&(*tree), str[i]);
}
}
void print_preorder(node * tree)
{
if (tree)
{
printf("%c",tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}
}
void deltree(node * tree)
{
if (tree)
{
deltree(tree->left);
deltree(tree->right);
free(tree);
}
}
int main()
{
node *root = NULL;
char ch;
string str;
while ( (ch = getchar()) )
{
if(ch == '$')
{
reverse(str.begin(), str.end());
construct(&root, str, str.size());
print_preorder(root);
printf("\n");
deltree(root);
break;
}
if(ch == '*')
{
reverse(str.begin(), str.end());
construct(&root, str, str.size());
print_preorder(root);
printf("\n");
deltree(root);
str.clear();
root = NULL;
continue;
}
if(ch >= 'A' && ch <= 'Z')
{
str.push_back(ch);
}
}
return 0;
}