按顺序输入建立二叉树


二叉树的顺序存储是指用一组地址连续的存储单元依次自上而下、自左向右存储完全二叉树上的结点元素
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 }

猜你喜欢

转载自www.cnblogs.com/AQhhhh/p/10844937.html