-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
127 lines (105 loc) · 2.54 KB
/
main.c
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
116
117
118
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
typedef struct node Node;
Node *newNode(int data);
void createTree(Node **tree);
void insertBST(Node **node, int data);
int treeIsEmpty(Node *node);
int isIdentical(Node *one, Node *two);
void invertTree(Node *root);
void preOrder(Node *root);
int returnKLargest(Node* root, int k);
int main(void) {
Node *rootOne;
Node *rootTwo;
createTree(&rootOne);
createTree(&rootTwo);
insertBST(&rootOne, 10);
insertBST(&rootOne, 5);
insertBST(&rootOne, 15);
insertBST(&rootOne, 2);
insertBST(&rootOne, 6);
insertBST(&rootOne, 12);
insertBST(&rootOne, 17);
insertBST(&rootTwo, 5);
insertBST(&rootTwo, 1);
insertBST(&rootTwo, 4);
// if (isIdentical(rootOne, rootTwo)) {
// puts("\nSÃO IGUAIS");
//} else {
// puts("\nNÃO SÃO IGUAIS");
//}
//invertTree(rootOne);
//preOrder(rootOne);
int data = returnKLargest(rootOne, 2);
return 0;
}
void createTree(Node **tree) { *tree = NULL; }
int treeIsEmpty(Node *node) { return node == NULL; }
Node *newNode(int data) {
// Aloca memória para newNode
Node *node = (Node *)malloc(sizeof(Node));
// Atribui o dado a newNode
node->data = data;
// Atribui NULL a left e right
node->left = NULL;
node->right = NULL;
return (node);
}
void insertBST(Node **node, int data) {
if (treeIsEmpty(*node)) {
*node = newNode(data);
} else {
if (data < (*node)->data) { // ESQUERDA SE FOR MENOR
insertBST(&(*node)->left, data);
}
if (data > (*node)->data) { // DIREITA SE FOR MAIOR
insertBST(&(*node)->right, data);
}
}
}
int isIdentical(Node *one, Node *two) {
if ((one == NULL) && (two == NULL)) {
return 1;
}
return ((one != NULL) && (two != NULL)) && ((one->data == two->data)) &&
isIdentical(one->left, two->left) &&
isIdentical(one->right, two->right);
}
int returnKLargest(Node* root, int k) {
int count = 0;
if (root == NULL) {
return 0;
}
int result = returnKLargest(root->right, k);
if (result != 0) {
return result;
}
count++;
if (count == k) {
return root->data;
}
return returnKLargest(root->left, k);
}
void invertTree(Node *root) {
if (root == NULL) {
return;
}
Node *temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
}
void preOrder(Node *root) {
if (root != NULL) {
printf("\n%i", root->data);
preOrder(root->left);
preOrder(root->right);
}
}