标签:二叉树的输出
例如:按树输出如下:
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define MAXSIZE 100 typedef char ElemType; typedef struct Node { ElemType data; struct Node *lchild; struct Node *rchild; }*BitTree,BitNode; void CreateBitTree2(BitTree *T,char str[]);//非递归创建二叉树 void LevelPrint(BitTree T);//按层次打印二叉树的结点 void TreePrint(BitTree T,int level);//按树状形式打印二叉树 void DestroyBitTree(BitTree *T);//销毁二叉树 #include "LinkBiTree.h" void CreateBitTree2(BitTree *T,char str[])//非递归创建二叉树 { char ch; BitTree stack[MAXSIZE]; int top = -1; int flag,k; BitNode *p; *T = NULL,k = 0; ch = str[k]; while(ch != '\0') { switch(ch) { case '(': stack[++top] = p; flag = 1; break; case ')': top--; break; case ',': flag = 2; break; default: p = (BitTree)malloc(sizeof(BitNode)); p->data = ch; p->lchild = NULL; p->rchild = NULL; if(*T == NULL) { *T = p; } else { switch(flag) { case 1: stack[top]->lchild = p; break; case 2: stack[top]->rchild = p; break; } } } ch = str[++k]; } } void LevelPrint(BitTree T)//按层次打印二叉树的结点 { BitTree queue[MAXSIZE]; BitNode *p; int front,rear; front = rear = -1; rear++; queue[rear] = T; while(front != rear) { front = (front+1)%MAXSIZE; p = queue[front]; printf("%c ",p->data); if(p->lchild != NULL) { rear = (rear+1)%MAXSIZE; queue[rear] = p->lchild ; } if(p->rchild != NULL) { rear = (rear+1)%MAXSIZE; queue[rear] = p->rchild ; } } } void TreePrint(BitTree T,int level)//按树状形式打印二叉树 { int i; if(T == NULL) { return; } TreePrint(T->rchild ,level+1); for(i = 0;i < level;i++) { printf(" "); } printf("%c\n",T->data); TreePrint(T->lchild ,level+1); } void DestroyBitTree(BitTree *T)//销毁二叉树 { if(*T) { if((*T)->lchild) { DestroyBitTree(&((*T)->lchild)); } if((*T)->rchild) { DestroyBitTree(&((*T)->rchild)); } free(*T); *T = NULL; } } #include "LinkBiTree.h" int main(void) { BitTree T,root; printf("利用括号嵌套建立二叉树:\n"); CreateBitTree2(&T,"(a(b(c,d),e(f(,g),h(i))))"); printf("按层次输出二叉树序列:\n"); LevelPrint(T); printf("\n"); printf("按树状打印二叉树:\n"); TreePrint(T,1); printf("\n"); printf("利用括号嵌套建立二叉树:\n"); CreateBitTree2(&root,"(A(B(D(,H),E(,I)),C(F,G)))"); printf("按层次输出二叉树序列:\n"); LevelPrint(root); printf("\n"); printf("按树状打印二叉树:\n"); TreePrint(root,1); printf("\n"); DestroyBitTree(&T); DestroyBitTree(&root); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:二叉树的输出
原文地址:http://blog.csdn.net/weichanjuan3/article/details/47091777