#include <iostream> #define maxSize 5 using namespace std; typedef struct BTNode { char data; struct BTNode * lchild; struct BTNode * rchild; }BTNode; BTNode * initBTNode() { BTNode *node = (BTNode*)malloc(sizeof(BTNode)); node->lchild=0; node->rchild=0; return node; } BTNode * init(BTNode *p) { BTNode *A=initBTNode(); BTNode *B=initBTNode(); BTNode *C=initBTNode(); BTNode *D=initBTNode(); BTNode *E=initBTNode(); BTNode *F=initBTNode(); A->data=‘A‘; B->data=‘B‘; C->data=‘C‘; D->data=‘D‘; E->data=‘E‘; F->data=‘F‘; C->lchild=E; C->rchild=F; B->lchild=D; A->rchild=C; A->lchild=B; p=A; return p; } void visit(BTNode *p) { cout << p->data << " "; } void preorder(BTNode *p) { if(p!=0) { visit(p); preorder(p->lchild); preorder(p->rchild); } } void inorder(BTNode *p) { if(p!=0) { inorder(p->lchild); visit(p); inorder(p->rchild); } } void postorder(BTNode *p) { if(p!=0) { postorder(p->lchild); postorder(p->rchild); visit(p); } } void level(BTNode *p) { int front,rear; BTNode *que[maxSize]; front = rear = 0; BTNode *q; if(p!=0) { rear=(rear+1)%maxSize; que[rear]=p; while(front!=rear) { front = (front+1)%maxSize; q=que[front]; visit(q); if(q->lchild!=0) { rear=(rear+1)%maxSize; que[rear]=q->lchild; } if(q->rchild!=0) { rear=(rear+1)%maxSize; que[rear]=q->rchild; } } } } int main(int argc, char* argv[]) { BTNode *node=new BTNode; BTNode *p=init(node); cout << "先序遍历:" ; preorder(p); cout << endl; cout << "中序遍历:" ; inorder(p); cout << endl; cout << "后序遍历:" ; postorder(p); cout << endl; cout << "层次遍历:" ; level(p); cout << endl; return 0; }
时间: 2024-10-26 04:53:18