二叉链表(孩子—兄弟)存储表示(代码实现)

输入的格式:

输入二叉树的先序序列。
提示:一棵二叉树的先序序列是一个字符串,若字符是‘#’,表示该二叉树是空树。

输出的格式:

输出有两行:
第一行为二叉树的中序遍历序列。
第二行为二叉树的叶子结点个数。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
//------二叉树的孩子-兄弟存储 -------
#define MAX_TREE_SIZE 100
#define OK 1
#define ERROR 0
typedef int Status;
int i=0; 
typedef struct CSNode  //树的二叉链表(孩子-兄弟)存储表示
{
	char data;
	struct CSNode *firstchild,*nextsibling; //分别为左孩子和孩子的兄弟   
}Tree,*CSTree;
CSTree creatTree() //树的二叉链表(孩子-兄弟)存储表示的输入 
{
    CSTree T;
    char datas;
    scanf("%c",&datas);
    if (datas == '#')
    {
        T = NULL;
    }
    else
    {
        T = (Tree*)malloc(sizeof(Tree));//分配空间 
        T->data = datas;//赋值 
        T->firstchild = creatTree();
        T->nextsibling = creatTree();
    }
    return T;
}
Status count(CSTree T){//计算叶子结点函数 
	if(T==NULL){
		return i;
	}
	else{
		if(T->firstchild==NULL&&T->nextsibling==NULL) i++;
		else{
			if(T->firstchild==NULL) count(T->nextsibling);
			else{
				if(T->nextsibling==NULL) count(T->firstchild);
			  else{
			  	count(T->firstchild);
			  	count(T->nextsibling);
			  }
			}
			
		}
	}
}
void putout(CSTree T){//以中序输出的函数 
	if(T==NULL) return;
	else{
		putout(T->firstchild);
		cout<<T->data;
		putout(T->nextsibling);
	}
} 
int main()
{
	CSTree A;
	A=creatTree();
	cout<<"中序遍历序列:"; 
	putout(A); 
	cout<<endl<<"叶子结点:"; 
	cout<<count(A);
	return 0;
}

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张立龙666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值