#include "tree.h" void initTree(Tree * T) { T->root = NULL; T->size = 0; } // insertTree helper static Node * createNode(int e) { Node * tmp = (Node *) malloc (sizeof(Node)); if (!tmp) { fprintf(stderr,"Node creation failed!\n"); exit(EXIT_FAILURE); } tmp->data = e; tmp->lchild = NULL; tmp->rchild = NULL; return tmp; } static void insertNode(Node * root, Node * new) { if (root->data > new->data) { if (!root->lchild) root->lchild = new; else insertNode(root->lchild,new); } else if (root->data < new->data) { if (!root->rchild) root->rchild = new; else insertNode(root->lchild,new); } else fprintf(stderr,"Binary tree can't hold two identical element.\n"); } bool insertTree(Tree * T, int e) { Node * tmp = createNode(e); if (T->size == 0) T->root = tmp; else insertNode(T->root,tmp); T->size++; return true; } void printTree(Node * root) { if (root->lchild) printTree(root->lchild); if (root->rchild) printTree(root->rchild); printf("%d ",root->data); } // freeTree helper void freeNode(Node * root) { Node * tmp = root; if (tmp->lchild) freeNode(tmp->lchild); if (tmp->rchild) freeNode(tmp->rchild); free(tmp); } void freeTree(Tree * T) { freeNode(T->root); T->size = 0; }