数据结构-树-二叉树-定义,遍历

来源:互联网 发布:centos更改ip地址 编辑:程序博客网 时间:2024/06/04 20:46
//定义//二叉链表typedef struct btnode{DataType data;struct btnode *lchild,*rchild;}*BinTree;BinTree root;//三叉链表typedef struct ttnode{DataType data;struct ttnode *lchild,*parent,*rchild;}*TBinTree;TBinTree root;//遍历//先序void preorder(BinTree bt){if (bt!=NULL){visit(bt);preorder(bt->lchild);preorder(bt->rchild);}}//中序void inorder (BinTree bt){if(bt!=NULL){inorder(bt->lchild);visit(bt);inorder(bt->rchild);}}//后序void postorder(BinTree bt){if (bt!=NULL){postorder(bt->lchild);postorder(bt->rchild);visit(bt);}}//求深度int Height(BinTree bt){int lh,rt;if (bt==NULL)return 0;else{lh=height(bt->lchild);rh=Height(bt->rchild);return 1+(lh>rh ? lh:rh);}}//层次遍历void levelorder(BinTree bt){LkQue Q;InitQueue(&Q);if (bt!=NULL){EnQueue(&Q,bt);while (!EmptyQueue(Q)){p=Gethead(&Q);outQueue(&Q);visit(p);if(p->lchild!=NULL)EnQueue(&Q,p->lchild);if(p->rchild!=NULL)EnQueue(&Q,p->rchild);}}}//遍历-非递归,中序visit调到pop(LS)和p=p->rchild之间void PreOrder(BinTree t){BinTree p;LkStk *LS;if (t==NULL)return;InitStack (LS);p=t;while(p!=NULL||!EmptyStack(LS)){if (p!=NULL){visit(p->data);Push(LS,p);p=p->lchild}else{p=GetTop(LS);Pop(LS);p=p->rchild}}}


 

0 0