PTA 先序序列创建二叉树,输出先序序列、中序序列、后序序列并输出叶子结点数

对于给定的二叉树,输出其先序序列、中序序列、后序序列并输出叶子结点数。

二叉树.png

输入格式:

二叉树的先序遍历序列。

提示:一棵二叉树的先序序列是一个字符串,若字符是‘#’,表示该二叉树是空树,否则该字符是相应结点的数据元素。

输出格式:

若是非空二叉树,则输出四行内容 第一行是二叉树的先序遍历序列; 第二行是二叉树的中序遍历序列; 第三行是二叉树的后序遍历序列; 第四行是叶子结点数;

若是空二叉树 只需输出叶子数0

输入样例1:

FCA##DB###EHM###G##

输出样例1:

FCADBEHMG
ACBDFMHEG
ABDCMHGEF
4

输入样例2:

#

输出样例2:

0

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 1000

typedef struct Tree{
	char data;
	struct Tree* lchild;
	struct Tree* rchild;
}DouTree, *Treelink;

Treelink createTree(char *preorder){
	static int index = 0; // 使用 static 修饰标识符 index 的目的是为了在递归调用过程中保持它的值,从而实现正确的遍历操作。
//如果不使用 static 关键字修饰 index,则会导致递归调用时每次都创建一个新的变量,并在返回上层时丢失先前的值。
	if(preorder[index] == '#' || preorder[index] == '\0'){ // 如果字符是 '#' 或者字符串终止符 '\0',表示该二叉树是空树
		index++;
		return NULL;
	}
	
	Treelink root = (Treelink)malloc(sizeof(DouTree)); // 创建一个新节点
	root->data = preorder[index++]; // 读取当前字符作为节点数据,并将索引 index 加一,指向下一个字符
	root->lchild = createTree(preorder); // 递归创建左子树
	root->rchild = createTree(preorder); // 递归创建右子树
	
	return root; // 返回根节点
}

void PreorderTraversal(Treelink root){
	if(root != NULL){
		printf("%c", root->data); // 先输出当前节点的数据
		PreorderTraversal(root->lchild); // 递归先序遍历左子树
		PreorderTraversal(root->rchild); // 递归先序遍历右子树
	}
}

void InorderTraversal(Treelink root){
	if(root != NULL){
		InorderTraversal(root->lchild); // 递归中序遍历左子树
		printf("%c", root->data); // 输出当前节点的数据
		InorderTraversal(root->rchild); // 递归中序遍历右子树
	}
}

void PostorderTraversal(Treelink root){
	if(root != NULL){
		PostorderTraversal(root->lchild); // 递归后序遍历左子树
		PostorderTraversal(root->rchild); // 递归后序遍历右子树
		printf("%c", root->data); // 输出当前节点的数据
	}
}

int countTreeleft(Treelink root){
	if(root == NULL) return 0; // 空树没有叶子节点
	else if (root->lchild == NULL && root->rchild ==  NULL) return 1; // 只有一个节点的树,即根节点,是叶子节点
	else return countTreeleft(root->lchild) + countTreeleft(root->rchild); // 递归计算左右子树的叶子节点数,并求和
}

int main(){
	char preorder[MAXSIZE];
	scanf("%s", preorder);
	Treelink root = createTree(preorder); // 根据先序遍历序列创建二叉树结构
	
	if(countTreeleft(root) != 0){ // 如果不是空树
		PreorderTraversal(root); // 先序遍历并输出结果
	    printf("\n");
	
	    InorderTraversal(root); // 中序遍历并输出结果
	    printf("\n");
	
	    PostorderTraversal(root); // 后序遍历并输出结果
	    printf("\n");
	} 
	
	printf("%d", countTreeleft(root)); // 输出叶子节点数
    free(root); // 释放树的内存

    return 0;
}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值