Binary sort tree Non-recursive insert code
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <malloc.h>5typedefstructnode6 {7 intVal;8 structnode*Lchild;9 structnode*Rchild;Ten}node,*Pnode; One A - intCreattree (Pnode *root,intArr[],intlen); - intInserttree (Pnode *root,intelem); the intPrinttree (Pnode root,intlen); - voidinorder (Pnode root); - - + - + intMainintargcChar*argv[]) A { at intArr[] = {5,8,7,9,4,Ten,1}; - intLen =sizeof(arr)/sizeof(arr[0]); - inti; - for(i=0; i<len;i++) - { -printf"%-3d", Arr[i]); in } -printf"\ n"); toPnode root =NULL; +Creattree (&Root,arr,len); - inorder (root); the return 0; * } $ Panax Notoginseng intCreattree (Pnode *root,intArr[],intlen) - { the inti; + for(i=0; i<len;i++) A { the Inserttree (Root,arr[i]); + } - return 1; $ } $ - intInserttree (Pnode *root,intelem) - { thePnode pnew =NULL; -Pnew = (Pnode) (calloc(1,sizeof(node));WuyiPnew->val =Elem; thePnew->lchild =NULL; -Pnew->rchild =NULL; WuPnode pcur =NULL; - if(*root = =NULL) About { $*root =pnew; - } - Else { -Pcur = *Root; A while(1) + { the if(Pcur->val >elem) - { $ if(pcur->lchild==NULL) the { thePcur->lchild =pnew; the Break; the } - Else { inPcur = pcur->Lchild; the Continue; the } About } the if(Pcur->val <=elem) the { the if(pcur->rchild==NULL) + { -Pcur->rchild =pnew; the Break;Bayi } the Else { thePcur = pcur->Rchild; - Continue; - } the } the } the } the return 1; - } the the voidInorder (Pnode root)//Post-post traversal the {94 if(Root) the { theInorder (root->lchild); theInorder (root->rchild);98printf"%d",root->val); About } -}
Benevolent training Camp March 29