二叉排序树非递归插入代码
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <malloc.h> 5 typedef struct node 6 { 7 int val; 8 struct node* lchild; 9 struct node* rchild; 10 }node,*pnode; 11 12 13 int creatTree(pnode *root,int arr[],int len); 14 int insertTree(pnode *root,int elem); 15 int printTree(pnode root,int len); 16 void inOrder(pnode root); 17 18 19 20 21 int main(int argc,char* argv[]) 22 { 23 int arr[] = {5,8,7,9,4,10,1}; 24 int len = sizeof(arr)/sizeof(arr[0]); 25 int i; 26 for(i=0;i<len;i++) 27 { 28 printf("%-3d",arr[i]); 29 } 30 printf("\n"); 31 pnode root = NULL; 32 creatTree(&root,arr,len); 33 inOrder(root); 34 return 0; 35 } 36 37 int creatTree(pnode *root,int arr[],int len) 38 { 39 int i; 40 for(i=0;i<len;i++) 41 { 42 insertTree(root,arr[i]); 43 } 44 return 1; 45 } 46 47 int insertTree(pnode *root,int elem) 48 { 49 pnode pnew = NULL; 50 pnew = (pnode)(calloc(1,sizeof(node))); 51 pnew->val = elem; 52 pnew->lchild = NULL; 53 pnew->rchild = NULL; 54 pnode pcur = NULL; 55 if(*root == NULL) 56 { 57 *root = pnew; 58 } 59 else { 60 pcur = *root; 61 while(1) 62 { 63 if(pcur->val > elem) 64 { 65 if(pcur->lchild==NULL) 66 { 67 pcur->lchild = pnew; 68 break; 69 } 70 else { 71 pcur = pcur->lchild; 72 continue; 73 } 74 } 75 if(pcur->val <= elem) 76 { 77 if(pcur->rchild==NULL) 78 { 79 pcur->rchild = pnew; 80 break; 81 } 82 else { 83 pcur = pcur->rchild; 84 continue; 85 } 86 } 87 } 88 } 89 return 1; 90 } 91 92 void inOrder(pnode root) //后序遍历 93 { 94 if(root) 95 { 96 inOrder(root->lchild); 97 inOrder(root->rchild); 98 printf("%d ",root->val); 99 } 100 }
时间: 2024-12-29 15:59:21