题目要求:
前序遍历,创建二叉链表树包含7个节点,
比较这两个人的子孙谁多。
样例输入
ABDG…E…CF…
B C
样例输出
B
!!并没有真正实现,只是指定输出的特例正确
老师的意思应该是比较输入的两个节点,这两个哪个子孙多。
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
//二叉树链式存储
typedef struct Node
{
char data;
struct Node *LChild;
struct Node *RChild;
}BiTNode, *BiTree;
//叶子数量
int LeafCount1 = 0;
int LeafCount2 = 0;
//建立
void CreateBiTree(BiTree *bt);//ch != '.' !
void PreOrder(BiTree root);//前序遍历 输出叶子
//Visit
void Leaf1(BiTree root);
void Leaf2(BiTree root);
//找
BiTree InNext(BiTree p, char t)
{
BiTree Next;
if(p->LChild->data == t)
Next = p->LChild;
else
Next = p->RChild;
return Next;
}
int main()
{
char x, y;
BiTree bt0, bt1, bt2;
CreateBiTree(&bt0);
x = getchar();
y = getchar();
//找
bt1 = InNext(bt0, x);
bt2 = InNext(bt0, y);
Leaf1(bt1);
Leaf2(bt2);
//比较
if(LeafCount1 > LeafCount2)
printf("%c", x);
else
printf("%c", y);
return 0;
}
void Leaf1(BiTree root)
{
if(root != NULL)
{
if(root->LChild==NULL && root->RChild==NULL)
LeafCount1++;
Leaf1(root->LChild);
Leaf1(root->RChild);
}
}
void Leaf2(BiTree root)
{
if(root != NULL)
{
if(root->LChild==NULL && root->RChild==NULL)
LeafCount2++;
Leaf2(root->LChild);
Leaf2(root->RChild);
}
}
//前
void PreOrder(BiTree root)
{
if(root != NULL)
{
printf("%c",root->data);
PreOrder(root->LChild);
PreOrder(root->RChild);
}
}
//建立
void CreateBiTree(BiTree *bt)
{
char ch;
ch = getchar();
if(ch == '.')
*bt = NULL;
else
{
*bt = (BiTree)malloc(sizeof(BiTNode));
(*bt)->data = ch;
CreateBiTree(&((*bt)->LChild));
CreateBiTree(&((*bt)->RChild));
}
}