From d837abf77f61a60a7601eac62d76d7573b912c5f Mon Sep 17 00:00:00 2001 From: Oleksandr Lytvyn Date: Tue, 17 Dec 2019 22:20:58 +0100 Subject: [PATCH] code for exam 2019 --- bst.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 bst.c diff --git a/bst.c b/bst.c new file mode 100644 index 0000000..07f060d --- /dev/null +++ b/bst.c @@ -0,0 +1,73 @@ +#include +#include + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ +struct node +{ + int data; + struct node* left; + struct node* right; +}; + +struct node* newNode(int data) +{ + struct node* node = (struct node*) + malloc(sizeof(struct node)); + node->data = data; + node->left = NULL; + node->right = NULL; + + return(node); +} + +struct node* insert(struct node* node, int data) +{ + /* 1. If the tree is empty, return a new, + single node */ + if (node == NULL) + return(newNode(data)); + else + { + /* 2. Otherwise, recur down the tree */ + if (data <= node->data) + node->left = insert(node->left, data); + else + node->right = insert(node->right, data); + + /* return the (unchanged) node pointer */ + return node; + } +} + +int minValue(struct node* node) { + struct node* current = node; + + /* loop down to find the leftmost leaf */ + while (current->left != NULL) { + current = current->left; + } + return(current->data); +} + + +void deleteTree(struct node* node) +{ + if (node == NULL) return; + + /* first delete both subtrees */ + deleteTree(node->left); + deleteTree(node->right); + + /* then delete the node */ + printf("\n Deleting node: %d", node->data); + free(node); +} + +int size(struct node* node) +{ + if (node==NULL) + return 0; + else + return(size(node->left) + 1 + size(node->right)); +} \ No newline at end of file