设为首页 加入收藏

TOP

C语言二叉树的建立,遍历(递归,非递归)
2014-11-23 22:53:49 来源: 作者: 【 】 浏览:2
Tags:语言 建立 遍历 递归

#include

#include

#define MAXSIZE 20

typedef struct BiTnode{

char data;

struct BiTnode *lchild,*rchild;

}BiTnode,*BiTree;

//浜 寤虹

int i = 0;

BiTree Create(BiTree t,char s[])

{

char ch;

ch = s[i++];

if(ch == ' ')

{

t = NULL;

}

else

{

if(!(t = (BiTree)malloc(sizeof(BiTnode))))

{

printf("fail to malloc!\n");

exit(0);

}

else

{

t->data = ch;

t->lchild = Create(t->lchild,s);

t->rchild = Create(t->rchild,s);

}

}

return t;

}

//涓

/*

void display(BiTree t)

{

BiTree stack[MAXSIZE],p;

int top = -1;

if(t)

{

p = t;

while(top > -1 || p)

{

while(p)

{

stack[++top] = p;

p = p->lchild;

}

if(top > -1)

{

p = stack[top--];

printf("%c ",p->data);

p = p->rchild;

}

}

printf("\n");

}

}

/*/

//

/*

void display(BiTree t)

{

BiTree stack[MAXSIZE],p;

int top = -1;

if(t)

{

p = t;

while(top > -1 || p)

{

while(p)

{

printf("%c ",p->data);

stack[++top] = p;

p = p->lchild;

}

if(top > -1)

{

p = stack[top--];

p = p->rchild;

}

}

printf("\n");

}

}

*//*

//

void display(BiTree t)

{

BiTree stack[MAXSIZE], p;

int top = -1;

if (t)

{

stack[++top] = t;

while (top > -1)

{

p = stack[top--];

printf("%c ", p->data);

if (p->rchild)

{

stack[++top] = p->rchild;

}

if (p->lchild)

{

stack[++top] = p->lchild;

}

}

printf("\n");

}

}*/

/*

//

void display(BiTree t)

{

BiTree m,stack[MAXSIZE];

int top = -1;

int flag;

if(t)

{

loop:

flag = 1;

m = NULL;

while(t)

{

stack[++top] = t;

t = t->lchild;

}

while(flag)

{

t = stack[top];

if(t->rchild == m)

{

printf("%c ",t->data);

top--;

m = t;

}

else

{

flag = 0;

t = t->rchild;

}

}

if(top>-1)

goto loop;

}

printf("\n");

}

*/

//

void display(BiTree t)

{

BiTree p = t, stack[MAXSIZE];

int tag[MAXSIZE];

int top = -1;

do

{

while(p != NULL)

{

stack[++top] = p;

tag[top] = 0;

p = p->lchild;

}

if(top > -1)

{

if(!tag[top])

{

p = stack[top];

p = p->rchild;

tag[top] = 1;

}

else

{

printf("%c ", stack[top--]->data);

}

}

}while((p != NULL)||(top > -1));

printf("\n");

}

//

/*void display(BiTree t)

{

if(t)

{

printf("%c ",t->data);

display(t->lchild);

display(t->rchild)锛

}

}*/

// 涓

/*void display(BiTree t)

{

if(t)

{

display(t->lchild);

printf("%c ",t->data);

display(t->rchild)锛

}

}*/

//

/*void display(BiTree t)

{

if(t)

{

display(t->lchild);

display(t->rchild);

printf("%c ",t->data);

}

}*/

int main(int argc,char *argv[])

{

BiTree t;

char s[] = "abc de f g ";

t = Create(t,s);

display(t);

return 0;

}

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇brk和sbrk . 下一篇hdu 3743 Frosh Week(离散化+树..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: