时间限制: 15 Sec 内存限制: 128 MB
提交: 1375 解决: 1019
题目描述
从键盘接收扩展先序序列,以二叉链表作为存储结构,建立二叉树。分别统计二叉树中叶子结点、度为1的结点、度为2的结点的个数,并输出。
第一行依次输出叶子结点个数、度为1的结点个数、度为2的结点个数,以空格隔开。
第二行连续输出叶子结点,中间不间隔。
样例输入 Copy
ABC##DE#G##F###
样例输出 Copy
3 2 2
CGF
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100
//节点类型定义
typedef struct Node{
char data;
struct Node* Lchild;
struct Node* Rchild;
}BiTNode, *BiTree;
//using namespace std;
typedef struct{ //定义栈
BiTNode node[MAX_SIZE];
int top;
}SeqStack;
int cnt1, cnt2;
//初始化栈
void InitStack(SeqStack *S)
{
S->top = -1;
}
//判空栈
int IsEmpty(SeqStack *S)
{
if(S->top == -1)
return 1;
return 0;
}
//进栈
int Push(SeqStack *S, BiTree p)
{
if(S->top == MAX_SIZE-1)
{
return 0;
}
else
{
S->top++;
S->node[S->top] = (*p);
return 1;
}
}
//出栈
int Pop (SeqStack *S, BiTNode *p)
{
if (S->top == -1)
{
return 0;
}
else
{
int c = S->top;
*p = S->node[c];
S->top--;
return 1;
}
}
//取栈顶元素
int Top(SeqStack *S, BiTNode *p)
{
if(S->top != -1)
{
*p = S->node[S->top];
return 1;
}
return 0;
}
//访问节点
void Visit(char p)
{
printf("%c\n", p);
}
//输出二叉树的叶子节点
void InOrderLeaf(BiTree root)
{
BiTree p = root;
if(p)
{
InOrderLeaf(root->Lchild);
if(root->Lchild == NULL && root->Rchild == NULL)
{
printf("%c", root->data);
}
InOrderLeaf(root->Rchild);
}
}
//统计度为一的节点
void Leaf1(BiTree root)
{
if(root)
{
Leaf1(root->Lchild);
Leaf1(root->Rchild);
if(root->Lchild == NULL && root->Rchild != NULL || root->Rchild == NULL && root->Lchild != NULL)
{
cnt1++;
}
}
}
//统计度为二的节点
void Leaf2(BiTree root)
{
if(root)
{
Leaf2(root->Lchild);
Leaf2(root->Rchild);
if(root->Lchild != NULL && root->Rchild != NULL)
cnt2++;
}
}
//统计叶子结点的数目
int Leaf0(BiTree root)
{
int nl, nr;
if(root == NULL)
return 0;
if(root->Lchild == NULL && root->Rchild == NULL)
return 1;
nl = Leaf0(root->Lchild);
nr = Leaf0(root->Rchild);
return nl + nr;
}
//用扩展先序遍历建立二叉链表
void CreateBiTree(BiTree *root)
{
char ch;
ch = getchar();
if(ch == '#')
*root = NULL;
else
{
(*root) = (BiTree)malloc(sizeof(BiTNode));
(*root)->data = ch;
CreateBiTree(&((*root)->Lchild));
CreateBiTree(&((*root)->Rchild));
}
}
int main()
{
BiTree root = NULL;
CreateBiTree(&root);
Leaf1(root);
Leaf2(root);
printf("%d %d %d\n", Leaf0(root), cnt1, cnt2);
InOrderLeaf(root);
return 0;
}