#include <stdio.h> #include <stdlib.h> #define MAXSIZE 100 typedef struct Node { int data; Node* lchild; Node* rchild; }Tnode; void creatTree(Tnode*& root) //创建树 { int n; printf("请输入节点值:(0结束):"); scanf("%d",&n); while(n!=0) { root = (Tnode*)malloc(sizeof(Tnode)); root->data = n; creatTree(root->lchild); creatTree(root->rchild); n = 0; } } void displayTree(Tnode* root) //括号表示法显示数 { if(!root) { printf("这是棵空树!/n"); exit(0); } printf("%d",root->data); if(root->lchild||root->rchild) { printf("("); if(root->lchild) { displayTree(root->lchild); } if(root->rchild) { printf(","); displayTree(root->rchild); } printf(")"); } } void destroyTree(Tnode*& root) //销毁树 { if(!root) { return; } if(root->lchild) { destroyTree(root->lchild); } if(root->rchild) { destroyTree(root->rchild); } free(root); } void printTree(Tnode* root) //层次遍历显示树 { Tnode* queue[MAXSIZE]; int front; int rear; rear = -1; front = -1; if(!root) { printf("这是棵空树!/n"); exit(0); } rear++; queue[rear] = root; while(front!=rear) { front = (front+1)%MAXSIZE; Tnode* p; p = queue[front]; printf("%d/t",queue[front]->data); if(p->lchild) { rear = (rear+1)%MAXSIZE; queue[rear] = p->lchild; } if(p->rchild) { rear = (rear+1)%MAXSIZE; queue[rear] = p->rchild; } } printf("/n"); } int main() { Tnode* root; creatTree(root); printf("括号表示法显示:"); printf("/n"); displayTree(root); printf("层次遍历显示:"); printTree(root); destroyTree(root); }