1 / 9

# 遍历算法应用 - PowerPoint PPT Presentation

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about ' 遍历算法应用' - yukio

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

• 按先序序列建立二叉树的算法

Status CreateBiTree(BiTree &T){

//按先序次序输入二叉树中的结点值(一个字符)，

//空格表示空树，

//构造二叉链表表示的二叉树T

scanf(&ch);

if (ch ==‘ ’) T = NULL;

else {

if (!(T = (BiTNode *)malloc(sizeof(BiTNode))))

exit(OVERFLOW);

T->data = ch;

CreateBiTree(T->lchild);

CreateBiTree(T->rchild);}

return OK;

}

E

D

C

B

A

G

T

A

B

C

D

E

F

G

• 若希望建立如下二叉树对应的存储结构，应输入的字符序列是

-

+

/

a

*

e

f

b

-

- + a _ _ * b _ _ - c _ _ d _ _ / e _ _ f _ _

c

d

B

C

D

E

F

G

#include <alloc.h>

#include <stdio.h>

typedef struct node

{ char data;

struct node *lchild,*rchild;

}JD;

void countleaf(JD *bt,int *count)

{ if(bt!=NULL)

{ if((bt->lchild==NULL)&&(bt->rchild==NULL))

{ (*count)++;

return; }

countleaf(bt->lchild,count);

countleaf(bt->rchild,count);

}

}

{ /* ABC00DE0G00F000 */

int count=0;

printf("count of leaf node is %d\n",count);}

JD *crt_bt_pre(JD *bt)

{ char ch;

printf("ch=");

scanf("%c",&ch);

if(ch==' ') bt=NULL;

else {

bt=(JD *)malloc(sizeof(JD));

bt->data=ch;

bt->lchild=crt_bt_pre(bt->lchild);

bt->rchild=crt_bt_pre(bt->rchild);}

return(bt);

}

void treedepth(JD *bt,int *l,int *h)

{

int l1=0,l2=0,h1=0,h2=0;

if(bt!=NULL)

{ (*l)++;

if (*l>*h) *h=*l;

treedepth(bt->lchild,&l1,&h1);

treedepth(bt->rchild,&l2,&h2);

if (h1>h2) *h=*h+h1;

else *h=*h+h2;

}

}

# include <alloc.h>

#include <stdio.h>

typedef struct node

{ char data;

struct node *lchild,*rchild;

}JD;

{ char ch;

printf("ch=");

scanf("%c",&ch);

getchar();

if(ch==' ') bt=NULL;

else {

bt=(JD *)malloc(sizeof(JD));

bt->data=ch;

bt->lchild=crt_bt_pre(bt->lchild);

bt->rchild=crt_bt_pre(bt->rchild); }

return(bt);

}

void main()

{ /* ABC00DE0G00F000 */

int level=0,high=0;

printf("depth of tree is %d\n",high);

}

• 具有n个结点的不同形态的二叉树有多少棵？

• 有 棵，如n=3时，有5种不同形态

• 已知结点先序序列和中序序列，是否可以唯一地确定一棵二叉树？

• 能，如先序序列ABCDEFG，中序序列CBEDAFG，对应的二叉树为

A

A

A

B

F

B

F

BCDE

C

D

FG

G

C

DE

G

E

Step1

Step2

Step3

• 已知结点先序序列和后序序列，是否可以唯一地确定一棵二叉树？

• 不能， 如先序序列ABCK，后序序列BKCA

• 已知结点中序序列和后序序列，是否可以唯一地确定一棵二叉树？

• 能，如中序序列BKCA，后序序列BKCA

A

A

BKC

BKC

A

A

C

A

C

K

BKC

BK

B

Step1

Step2

Step3