树的创建
一 递归法创建树
1 void CreateTree(BTree& T) 2 { 3 int data; 4 scanf("%d",&data); 5 if (data == -1) //输入-1时结束递归 6 T = NULL; 7 else{ 8 T = new BTNode; 9 T->data = data; 10 CreateTree(T->lchild); //建立左子树 11 CreateTree(T->rchild);//建立右子树 12 } 13 }
二 树的遍历
1.先序遍历
1 void PreOrder(BTree T) 2 { 3 if(T!=NULL){ 4 printf("%d ",T->data); 5 PreOrder(T->lchild); 6 PreOrder(T->rchild); 7 } 8 }
2.中序遍历
1 void InOrder(BTree T) 2 { 3 if(T!=NULL){ 4 InOrder(T->lchild); 5 printf("%d ",T->data); 6 InOrder(T->rchild); 7 } 8 }
3.后序遍历
1 void PostOrder(BTree T) 2 { 3 if(T!=NULL){ 4 PostOrder(T->lchild); 5 PostOrder(T->rchild); 6 printf("%d ",T->data); 7 } 8 }
三 运行截图
四 完整代码
1 #include<stdio.h> 2 using namespace std; 3 4 typedef struct BTNode 5 { 6 int data; 7 struct BTNode *lchild, *rchild; 8 }BTNode,*BTree; 9 10 void PreOrder(BTree T) 11 { 12 if(T!=NULL){ 13 printf("%d ",T->data); 14 PreOrder(T->lchild); 15 PreOrder(T->rchild); 16 } 17 } 18 19 void InOrder(BTree T) 20 { 21 if(T!=NULL){ 22 InOrder(T->lchild); 23 printf("%d ",T->data); 24 InOrder(T->rchild); 25 } 26 } 27 28 void PostOrder(BTree T) 29 { 30 if(T!=NULL){ 31 PostOrder(T->lchild); 32 PostOrder(T->rchild); 33 printf("%d ",T->data); 34 } 35 } 36 37 void CreateTree(BTree& T) 38 { 39 int data; 40 scanf("%d",&data); 41 if (data == -1) //输入-1时结束递归 42 T = NULL; 43 else{ 44 T = new BTNode; 45 T->data = data; 46 CreateTree(T->lchild); //建立左子树 47 CreateTree(T->rchild);//建立右子树 48 } 49 } 50 51 int main() 52 { 53 BTree T; 54 CreateTree(T); 55 printf("先序遍历:"); 56 PreOrder(T); 57 printf("\n"); 58 printf("中序遍历:"); 59 InOrder(T); 60 printf("\n"); 61 printf("后序遍历:"); 62 PostOrder(T); 63 printf("\n"); 64 return 0; 65 }