#include<stdio.h> #include<stdlib.h> typedef struct bitnode{ char data; struct bitnode *lchild,*rchild; }nitnode,*bitree; typedef struct { bitree *top; bitree *base; int stacksize; }sqstack; int initstack(sqstack &s) { s.base=(bitree *)malloc(10*sizeof(bitree)); if(!s.base) return 0; s.top=s.base; s.stacksize=10; return 1; } int push(sqstack &s,bitree p) { if(s.top-s.base==s.stacksize){ s.base=(bitree*)realloc(s.base,15*sizeof(bitree)); if(!s.base) return 0; s.top=s.base+10; s.stacksize=15;} *s.top++=p; return 1; } int pop(sqstack &s,bitree &p) { if(s.top==s.base) return 0; p=*--s.top; return 1; } int creattree(bitree &t) { char ch; scanf("%c",&ch); if(ch=='#') t=NULL; else { t=(bitree)malloc(sizeof(bitnode)); t->data=ch; creattree(t->lchild); creattree(t->rchild); } return 1; } int inorder(bitree &t){ bitree p; sqstack s; initstack(s); p=(bitree)malloc(sizeof(bitnode)); p=t; while(!(p==NULL)||(s.base!=s.top)) { if(!(p==NULL)) { push(s,p); p=p->lchild; } else { pop(s,p); printf("%c",p->data); p=p->rchild; } } return 0; } int main(){ bitree t; creattree(t); inorder(t); return 0; }
二叉树的另三种表示法:
//双亲表示法 typedef struct ptnode{ int data; int parent; } typedef structP{ ptnode node[20]; int r,n; //根的位置和结点数 }ptree;
//孩子表示法 typedef struct ctnode{ int child; // 孩子的位置; struct ctnode *next; }*childptr; typedef struct{ int data; childptr firstchild; }ctbox; typedef struct{ ctbox node[20]; int n,r;//结点数和根的位置 } //孩子兄弟表示法 typedef struct csnode{ int data; struct csnode *firstchild,*nestsibiling; }csnode,*cstree;
bitree swaptree(bitree b){ bitree t,t1,t2; if(b==NULL) t=NULL; else{ t=(bitree)malloc(sizeof(bitnode)); t->data=b->data; t1=swaptree(b->lchild); t2=swaptree(b->rchild); t->lchild=t2; t->rchild=t1; } return t; } // 将各结点的左右子树互换 int high(bitree b){ int h1,h2; if(b==NULL) return 0; else{ h1=high(b->lchild); h2=high(b->rchild); if(h1>h2) return (h1+1); else return (h2+1); } } //求二叉树的高度