按順序輸入建立二叉樹



二叉樹的順序存儲是指用一組地址連續的存儲單元依次自上而下、自左向右存儲完全二叉樹上的結點元素
1
#include<stdio.h> 2 #include<stdlib.h> 3 typedef struct btree 4 { 5 int data; 6 struct btree *right,*left; 7 8 }tree; 9 int s[1001],n; 10 void build_tree(tree* &t,int x)//建立二叉樹,可以用引用也可以用二重指針 11 { 12 if(x>n||s[x]==0)//0或者超出元素就算結點為空 13 { 14 t=NULL; 15 return; 16 } 17 t=(tree*)malloc(sizeof(tree)); 18 t->data=s[x]; 19 build_tree(t->left,2*x); 20 build_tree(t->right,2*x+1); 21 } 22 int deep(tree* t)//樹高 23 { 24 if(t==NULL) 25 return 0; 26 int l=0,r=0; 27 l=deep(t->left)+1; 28 r=deep(t->right)+1; 29 return l>r?l:r;//分別往左右兩邊遍歷,比較兩邊最大的節點數就是樹的高度。 30 } 31 void preorder(tree* t)//先序遍歷 32 { 33 if(t) 34 { 35 printf(" %d",t->data); 36 preorder(t->left); 37 preorder(t->right); 38 } 39 } 40 void inorder(tree* t)//中序遍歷 41 { 42 if(t) 43 { 44 inorder(t->left); 45 printf(" %d",t->data); 46 inorder(t->right); 47 } 48 } 49 void postorder(tree* t)//后序遍歷 50 { 51 if(t) 52 { 53 postorder(t->left); 54 postorder(t->right); 55 printf(" %d",t->data); 56 } 57 } 58 int main() 59 { 60 tree *tr; 61 tr=NULL; 62 n=1; 63 while(scanf("%d",&s[n]))//先將數據入隊,然后存入數組 64 { 65 if(s[n]==-1) 66 { 67 n--; 68 break; 69 } 70 n++; 71 } 72 build_tree(tr,1);//建立二叉樹 73 preorder(tr); 74 printf("\n"); 75 inorder(tr); 76 printf("\n"); 77 postorder(tr); 78 printf("\n"); 79 return 0; 80 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM