Recursive size

This commit is contained in:
Imbus 2024-03-27 07:02:19 +01:00
parent 5b7efc9ef3
commit 9eeba598e7
3 changed files with 6 additions and 18 deletions

View file

@ -5,10 +5,10 @@
int main(void) { int main(void) {
Tree tree = {NULL}; Tree tree = {NULL};
printf("Tree size: %d\n", tree_size(&tree)); printf("Tree size: %d\n", tree_size(tree.root));
tree_insert(&tree, 1); tree_insert(&tree, 1);
tree_insert(&tree, 2); tree_insert(&tree, 2);
tree_insert(&tree, 3); tree_insert(&tree, 3);
printf("Tree size: %d\n", tree_size(&tree)); printf("Tree size: %d\n", tree_size(tree.root));
return 0; return 0;
} }

View file

@ -49,22 +49,10 @@ int tree_remove(Tree *tree, int data) { return 1; }
int tree_clear(Tree *tree) { return 1; } int tree_clear(Tree *tree) { return 1; }
int tree_size(Tree *tree) { int tree_size(Node *node) {
if (tree->root == NULL) { if (node == NULL) {
return 0; return 0;
} }
int size = 0; return 1 + tree_size(node->left) + tree_size(node->right);
Node *current = tree->root;
while (current != NULL) {
size++;
if (current->left != NULL) {
current = current->left;
} else if (current->right != NULL) {
current = current->right;
} else {
current = NULL;
}
}
return size;
} }

View file

@ -19,4 +19,4 @@ typedef struct Tree Tree;
int tree_insert(Tree *tree, int data); int tree_insert(Tree *tree, int data);
int tree_remove(Tree *tree, int data); int tree_remove(Tree *tree, int data);
int tree_clear(Tree *tree); int tree_clear(Tree *tree);
int tree_size(Tree *tree); int tree_size(Node *node);