二叉树最长路径

(二叉树查找最长路径)

建立一棵树,输出最长路径,如果有多条输出最左端的路

下面是代码段:
#include<stdio.h>
#include<malloc.h>
#define null 0

struct Btree{
char data;
Btree *lchild;
Btree *rchild;
};

Btree *setup()//建立二叉树
{
char ch;
Btree *bt;
printf(“please input ch:”);
ch=getchar();
getchar();
if(ch!=’.’)
{
bt=(Btree *)malloc(sizeof(Btree));
bt->data=ch;
bt->lchild=setup();
bt->rchild=setup();
}
else
return null;
}

int Find(Btree *root)//为二叉树的节点赋层号
{
if(!root->lchild&&!root->rchild)
{
return 0;
}
else if(root->lchild)
return Find(root->lchild)+1;
else if(root->rchild)
return Find(root->rchild)+1;
else
{
if(Find(root->lchild)>Find(root->rchild))
return Find(root->lchild)+1;
else
return Find(root->rchild)+1;
}
}

void Print(Btree *root)//输出最长路径
{
if(root->lchild&&root->rchild)
{
printf("%c\t",root->data);
if(Find(root->lchild)>=Find(root->rchild))
Print(root->lchild);
else
Print(root->rchild);
}
else if(root->lchild)
{
printf("%c\t",root->data);
Print(root->lchild);
}
else if(root->rchild)
{
printf("%c\t",root->data);
Print(root->rchild);
}
else
printf("%c\t",root->data);
}

int main()
{
Btree *b1;
b1=setup();
Print(b1);
return 0;
}

猜你喜欢

转载自blog.csdn.net/cobracanary/article/details/84495310
今日推荐