后序遍历求解二叉树的高度

来源:互联网 发布:世界银行网站数据库 编辑:程序博客网 时间:2024/05/08 07:19
#include <stdio.h>#include <stdlib.h>#include <math.h>#define MAX 100 typedef struct BiTNode {char data;struct BiTNode *lchild,*rchild;}BiTNode,*BiTree;typedef struct {BiTree *base;int top;int stacksize;}SqStack;void InitStack(SqStack &S){//构造一个空栈 S.base=(BiTree *)malloc(MAX*sizeof(BiTree));if(!S.base)exit(0);S.top=0;S.stacksize=MAX;}void Push(SqStack &S,BiTree e){//入栈操作 if(S.top>=S.stacksize){S.base=(BiTree *)realloc(S.base,(MAX+10)*sizeof(BiTree));S.stacksize+=10;}S.base[S.top++]=e;}void Pop(SqStack &S,BiTree &e){//出栈操作 if(S.top==0)return;e=S.base[--S.top];}int StackEmpty(SqStack S){//栈的判空操作 if(S.top==0)return 1;return 0;}int GetTop(SqStack S,BiTree &e){//取栈顶元素 if(S.top==0)return 0;e=S.base[--S.top];return 1;}void CreatBiTree(BiTree &bt){//输入完全二叉树的先序序列,建立二叉树的二叉链表char ch;ch=getchar();if(ch=='#')bt=NULL;else{bt=(BiTree)malloc(sizeof(BiTNode));bt->data=ch;CreatBiTree(bt->lchild);CreatBiTree(bt->rchild);}}void PostOrderTraverse(BiTree bt){//利用后序遍历求解二叉树的高度int tmp=0;BiTree p,q;SqStack S;if(!bt){printf("0\n");return;}if(bt){InitStack(S);Push(S,NULL);p=bt;q=NULL;while(p || !StackEmpty(S)){if(p && p!=q){Push(S,p);if(S.top>tmp)//记录最大栈顶长度tmp=S.top;p=p->lchild;}else{Pop(S,p);if(!StackEmpty(S)){if(p->rchild && p->rchild!=q){Push(S,p);p=p->rchild;}else{//printf("%c ",p->data);q=p;}}}}printf("%d\n",tmp-1);//结点最大栈长即为二叉树的高度 }}int main(){BiTree bt;printf("输入完全二叉树的先序序列,建立二叉树的二叉链表:\n");CreatBiTree(bt);printf("所输入二叉树的高度是:");PostOrderTraverse(bt);return 0;}

0 0
原创粉丝点击