二叉树的创建及其遍历
#include <stdio.h> #include <stdlib.h> struct Bintree { char info; struct Bintree *lchild,*rchild; }; typedef struct Bintree *BinTreeNode; typedef struct Node *PNode;//栈的存储结构 struct Node { BinTreeNode c; PNode link; }; struct LinkStack//链接栈类型定义 { PNode top;//指向栈顶元素 }; typedef struct LinkStack *PLStack;//链接栈类型定的指针类型 PLStack Cstack()//创建空栈 { PLStack plstack; plstack=(PLStack)malloc(sizeof(PLStack)); if(plstack!=NULL) plstack->top=NULL; else printf("out of space") ; return plstack; } int isemptystack(PLStack plstack) //判断是否是空栈 { return (plstack->top==NULL); } void push(PLStack plstack, BinTreeNode x) //进栈运算 { PNode p; p=(PNode)malloc(sizeof(struct Node)); if(p==NULL) printf("out of space"); else { p->c=x; p->link=plstack->top; plstack->top=p; } } void pop (PLStack plstack)//出栈运算 { PNode p; if(isemptystack(plstack)) //判断栈是否为空,空栈不进行任何操作, //否则出栈运算,修改指针 printf("Empty stack pop.\n"); else { p=plstack->top; printf("%c",p->c->info); plstack->top=plstack->top->link; free(p); } } BinTreeNode top(PLStack plstack)//取栈顶元素 { if(plstack->top==NULL)//判断栈顶是否空栈 printf("Stack is Empty"); else { return (plstack->top->c); } } BinTreeNode CBintree() { char c; BinTreeNode p; scanf("%c",&c); getchar(); if(c!='#') { p=(BinTreeNode)malloc(sizeof(BinTreeNode)); p->info=c; p->lchild=CBintree(); p->rchild=CBintree(); } else p=NULL; return p; } void npreOreder(BinTreeNode t) //先根次序次序周游 { PLStack s; BinTreeNode c; if(t==NULL) return; s=Cstack(); push(s,t); while(!isemptystack(s)) { c=top(s);pop(s); if(c!=NULL) { if(c->rchild!=NULL) push(s,c->rchild); if(c->lchild!=NULL) push(s,c->lchild); } } } void ninOder(BinTreeNode t) //中根次序周游 { PLStack s=Cstack(); BinTreeNode c=t; if(c==NULL) return; do{ while(c!=NULL){push(s,c);c=c->lchild; } c=top(s);pop(s);c=c->rchild; }while(c!=NULL||!isemptystack(s)); } void npostOrder(BinTreeNode t) { PLStack s=Cstack(); BinTreeNode p=t; while(p!=NULL||!isemptystack(s)) { while(p!=NULL){ push(s,p) ; p=p->lchild?p->lchild:p->rchild; } p=top(s); pop(s); if(!isemptystack(s)&&top(s)->lchild==p) p=top(s)->rchild; else p=NULL; } } int dfs_Tree(BinTreeNode t,int a){ if(t==NULL){ return a; } if(t->lchild!=NULL)return dfs_Tree(t->lchild,a+1); if(t->rchild!=NULL)return dfs_Tree(t->rchild,a+1); return a; } int main() { BinTreeNode root=(BinTreeNode)malloc(sizeof(BinTreeNode)); root=CBintree(); printf("先根"); npreOreder(root); printf("中根"); ninOder(root); printf("后根"); npostOrder(root); printf("\n%d",dfs_Tree(root,1)); return 0; }