#include <stdio.h> #include <stdlib.h>/** data structure: Two-fork search tree, left child < parent < Right child * c language implementation * 2015-9-13*/typedef struct treenode *ptrtonode;typedef ptrtonode tree;typedef ptrtonode position;struct treenode {int element; tree left; //node left child tree right; //node right child};/** make two fork tree empty, use recursive release memory Method */tree makeempty ( tree t) {if (t != null) {makeempty (t->left); Makeempty (t->right); free (T);} Return null;} /** Find an element */position find (int x, tree t) {if (t == null) {return null;} if (x < t->element) {return find (x, t->left);} else if (x>t->element) {return find (x, t->right);} Else {return t;}} /** Find minimum value */position findmin (tree t) {if (T == null) {return null;} else if (T->left == null) {return t;}Else {findmin (T->left);}} /** looking for maximum value */position findmax (tree t) {if (T == null) {return null;} else if (T->right == null) {return t;} Else {findmax (T->right);}} /** inserting elements into a two-fork tree */tree insert (int x, tree t) {if (t == null) {T = (Tree) malloc (sizeof (Struct treenode));if (t == null) {printf ("Out of memory!\n "); exit (1);} else {t->element = x; T->left = t->right = null;}} else if (x < t->element) {t->left = insert (X, T->Left);} else if (x > t->element) {t->right = insert (X, T->Right);} Return t;} /** Delete an element in the tree */tree delete (int x, tree t) {position tmpcell;if (T == null) {printf ("no such element!\n"); exit (2);} Else if (x < t->element) {t->left = delete (x, t->left);} else if (x > t->element) {t->right = delete (X, T->Right);} else if (t->left && t->right) {tmpcell = findmin (T->Right) ; t->element = tmpcell->element; T->right = delete (t->element, t->right);} else {tmpcell = t;if (T->left == null) {t = t->right;} else if (T->right == null) {t = t->left;} Free (Tmpcell);}} /** Pre-sequence traversal prints all elements */void printwithpreorder (tree t) {if (t != null) {printf ("%d\t ", t->element); Printwithpreorder (T->left); Printwithpreorder (T->right);}} /** sequence traversal prints all elements */void printwithinorder (tree t) {if (t != null) { Printwithinorder (T->left);p rintf ("%d\t", t->element); Printwithinorder(T->right);}} /** post-traverse print all elements */void printwithpostorder (tree t) {if (t != null) { Printwithpostorder (T->left); Printwithpostorder (t->right);p rintf ("%d\t", t->element);}} /** test Program */int main () {tree t = null; T = insert (1, t); T = insert (0, t); T = insert ( -1, t); T = insert (20, t); T = insert ( -10, t); T = insert (10, t); T = insert (2, t); T = insert (5, t);p rintf ("min is %d\n", findmin (T)->element);p rintf ("Max Is %d\n ", findmax (t)->element);//The following method prints all the node elements Printwithinorder (t); return 0;}
This blog post continues to update ...
C Language Implementation two fork find tree