二叉樹的遞迴建立,二叉樹查詢,二叉樹結點的刪除程式碼
阿新 • • 發佈:2021-01-01
二叉樹的遞迴建立
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 struct tree 5 { 6 int data; 7 struct tree* left; 8 struct tree* right; 9 }; 10 11 typedef struct tree treenode; 12 typedef treenode* btree; 13 14 btree createbtree(int* data,int pos) 15 { 16 btree newnode;17 18 if(data[pos] == 0 || pos > 15) 19 return NULL; 20 else 21 { 22 newnode = (btree)malloc(sizeof(treenode)); 23 newnode->data = data[pos]; 24 25 newnode->left = createbtree(data,2*pos); 26 newnode->right = createbtree(data,2*pos + 1); 27 return newnode; 28 } 29 } 30 31 void printbtree(btree ptr) 32 { 33 if(ptr != NULL) 34 { 35 printbtree(ptr->left); 36 printf("[%2d]",ptr->data); 37 printbtree(ptr->right); 38 } 39 } 40 41 int main() 42 { 43 btree root = NULL;44 int i; 45 46 int data[16] = {0,5,4,6,2,0,0,8,1,3,0,0,0,0,7,9}; 47 root = createbtree(data,1); 48 printf("陣列的節點內容 \n"); 49 for(i = 1;i < 16;i++) 50 printf("[%2d]",data[i]); 51 printf("\n"); 52 printf("樹的結點內容 \n"); 53 printbtree(root); 54 printf("\n"); 55 return 0; 56 }