确定根节点在中序中的位置,将中序序列分为两个子序列,递归处理直到所处理的子序列只剩下一个元素
BTnode *CreateBt(char pre[],char in[],int l1,int r1,int l2,int r2){ BTnode *s; int i; if(l1>r1) return NULL; //递归结束条件 s=(BTnode *)malloc(sizeof(BTnode)); s->lchild=S->rchild=NULL; for(i=l2;i<=r2;i++) if(in[i]==pre[l1]) break; s->data=in[i]; //确定根节点位置 s->lchild=CreateBt(pre,in,l1+1,l1+i-l2,l2,i-1); s->rchild=CreateBt(pre,in,l1+i-l2+1,r1,i+1,r2); return s; }实质遍历二叉树
int n=0; //先序遍历 void count(BTnode *p){ if(p){ ++n; count(p->lchild); count(p->rchild); } } //后序遍历 int count(BTnode *p){ int n1,n2; if(p==NULL){ return 0; } else { n1=count(p->lchild); n2=count(p->rchild); return 1+n1+n2; } }遍历过程中只在遇到叶子结点的时候对其右指针进行操作
void link(BTnode *p,BTnode *&head,BTnode *&tail){ if(p){ if(p->lchild==NULL&&p->rchild==NULL){ if(head==NULL){ //找到第一个叶子结点,确定链表头 head=p; tail=p; } else { //不是第一个叶子结点,则尾插法构建链表 tail->rchild=p; tail=p; } } link(p->lchild,head,tail); //先序遍历 link(p->rchild,head,tail) ; } }修改二叉链表结点数据结构,将所有结点的parent指针指向双亲结点,打印所有节点到根节点的路径。
typedef struct BTnode{ char data; struct BTnode *rchild; struct BTnode *lchild; struct BTnode *parent; }BTnode; //给parent指针赋值 void triBTree(BTnode *p,BTnode *q){//q始终指向当前访问结点p的双亲结点 if(p){ p->parent=q; q=p; triBTree(p->lchild,q); triBTree(p->rchild,q); } } //任给一个节点求其到根节点的路径 void printPath(BTnode *p){ while(p){ printf("%d",p->data); p=p->parent; } }只需将根节点移动到整个序列的末尾,然后继续递归处理序列的前一半和后一半
void change(char pre[],int l1,int r1,char post[],int l2,int r2){ if(l1<=r1){ post[r2]=pre[l1]; change(pre,l1+1,(l1+1+r1)/2,post,l2,(l2+r2-1)/2); change(pre,(l1+1+r1)/2+1,r1,post,(l2+r2-1)/2+1,r2-1); } }沿着t的右子树链一直走下去,直到遇到其右指针为右线索的节点为止
TBTnode *inLast(TBTnode *t){ TBTnode *p=t; while(p&&!p->rtag) p=p->rchild; return p; }若t有左线索,则其左线索所指结点即为中序前驱;若无左线索,则其左子树中中序最后一个节点为它的中序前驱
TBTnode *inPrior(TBTnode *t){ TBTnode *p=t->lchild; if(p&&!t->ltag) p=inLast(p); return p; }分三种情况:1、节点有左孩子 2、节点只有右孩子 3、节点没有孩子,此时其前序后继是此节点的右线索走到无右线索节点这个节点就是前序后继
TBTnode *preNext(TBTnode *t){ TBTnode *p; if(!t->ltag) p=t->lchild; else if(!t->rtag) p=t->rchild; else{ p=t; while(p&&p->rtag) p=p->rchild; if(p) p=p->rchild; } return p; }
