From f3a32c4c79a9e4343cd172545da2da3787b4a80c Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Wed, 27 Mar 2024 10:00:11 +0100 Subject: [PATCH] Fixing clear --- src/main.c | 20 ++++++++++++++++++-- src/tree.c | 27 ++++++++++++++++++++++----- src/tree.h | 22 ++++++++++++++++++++-- 3 files changed, 60 insertions(+), 9 deletions(-) diff --git a/src/main.c b/src/main.c index 2f57fdb..38f9c76 100644 --- a/src/main.c +++ b/src/main.c @@ -5,12 +5,28 @@ int main(void) { Tree tree = {NULL}; - printf("Tree size: %d\n", tree_size(tree.root)); + + // Some test insertions tree_insert(&tree, 1); tree_insert(&tree, 2); tree_insert(&tree, 3); + + // Check size and print inorder printf("Tree size: %d\n", tree_size(tree.root)); + tree_inorder(tree.root); + printf("Tree contains 2: %d\n", tree_contains(tree.root, 2)); - // tree_clear(&tree.root); // Something is fishy here + + // Clear the tree + tree_clear(&tree); + + // Check if the tree is really empty + if (tree.root == NULL) printf("Tree is empty\n"); + else printf("Tree is not empty: %d\n", tree.root->data); + + // Check size and print inorder + printf("Tree size: %d\n", tree_size(tree.root)); + tree_inorder(tree.root); + return 0; } diff --git a/src/tree.c b/src/tree.c index 6353fee..43e2891 100644 --- a/src/tree.c +++ b/src/tree.c @@ -65,17 +65,34 @@ int tree_remove(Node **node, int data) { return 0; } -int tree_clear(Node *node) { +void tree_clear(Tree *tree) { + if (tree->root == NULL) + return; + + node_clear(tree->root); + tree->root = NULL; +} + +void node_clear(Node *node) { if (node == NULL) - return 0; + return; if (node->left != NULL) - tree_clear(node->left); + node_clear(node->left); + if (node->right != NULL) - tree_clear(node->right); + node_clear(node->right); free(node); - return 0; +} + +void tree_inorder(Node *node) { + if (node == NULL) + return; + + tree_inorder(node->left); + printf("%d ", node->data); + tree_inorder(node->right); } int tree_size(Node *node) { diff --git a/src/tree.h b/src/tree.h index 54d3cfa..ef90695 100644 --- a/src/tree.h +++ b/src/tree.h @@ -1,4 +1,5 @@ -#pragma once +#ifndef TREE_H +#define TREE_H #include #include @@ -17,8 +18,25 @@ struct Tree { }; typedef struct Tree Tree; +// Insert some data into the tree int tree_insert(Tree *tree, int data); + +// Remove some data from the tree int tree_remove(Node **node, int data); -int tree_clear(Node *node); + +// Clear the tree (this wraps node_clear) +void tree_clear(Tree *tree); + +// Recursively clear from a certain node +void node_clear(Node *node); + +// Get the size of the tree int tree_size(Node *node); + +// Check if the tree contains some data bool tree_contains(Node *node, int data); + +// Print the tree in order +void tree_inorder(Node *node); + +#endif // TREE_H \ No newline at end of file