其他分享
首页 > 其他分享> > 7-54 二叉树的基本运算 (10 分)

7-54 二叉树的基本运算 (10 分)

作者:互联网

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 100
typedef struct TNode* Position;
typedef Position BinTree;
struct TNode {
	char Data;
	BinTree Left;
	BinTree Right;
};
void CreatBinTree(BinTree* BT,char* str1) {
	BinTree str2[MaxSize];
	BinTree p = *BT = NULL;
	int k = 0, j = 0, top = -1;
	char ch = str1[j];
	while (ch != '\0') {
		switch (ch) {
		case'(':str2[++top] = p; k = 1; break;
		case')':top--; break;
		case',':k = 2; break;
		default:
			p = (BinTree)malloc(sizeof(struct TNode));
			p->Data = ch;
			p->Left = p->Right = NULL;
			if (*BT == NULL)*BT = p;
			else k == 1 ? str2[top]->Left = p : str2[top]->Right = p;
		}
		ch = str1[++j];
	}
}
void InorderTraversal(BinTree BT) {
	if (BT) {
		InorderTraversal(BT->Left);
		printf("%c ", BT->Data);
		InorderTraversal(BT->Right);
	}
}
int GetHeight(BinTree BT) {
	int HL, HR, MaxH;
	if (BT) {
		HL = GetHeight(BT->Left);
		HR = GetHeight(BT->Right);
		MaxH = HL > HR ? HL : HR;
		return(MaxH + 1);
	}
	else return 0;
}
int Leaves_num(BinTree BT) {
	if (BT == NULL)return 0;
	if (BT->Left == NULL && BT->Right == NULL)
		return 1;
	return(Leaves_num(BT->Left) + Leaves_num(BT->Right));
}
void Exchange(BinTree* BT) {
	if (*BT) {
		BinTree temp;
		temp = (*BT)->Left;
		(*BT)->Left = (*BT)->Right;
		(*BT)->Right = temp;
		Exchange(&(*BT)->Left);
		Exchange(&(*BT)->Right);
	}
}
void Display(BinTree BT) {
	if (BT != NULL)printf("%c", BT->Data);
	if (BT->Left != NULL || BT->Right != NULL) {
		printf("(");
		if (BT->Left != NULL)Display(BT->Left);
		if (BT->Right != NULL) {
			printf(",");
			Display(BT->Right);
		}
		printf(")");
	}
}
int main() {
	int Height;
	int number;
	BinTree root = NULL;
	char str1[MaxSize] = { 0 };
	scanf("%s", str1);
	CreatBinTree(&root, str1);
	InorderTraversal(root);
	printf("\n");
	Height = GetHeight(root);
	printf("%d\n", Height);
	number = Leaves_num(root);
	printf("%d\n", number);
	Exchange(&root);
	Display(root);
	system("pause");
	return 0;
}

本习题为二叉树的基本运算练习,要求依次实现如下功能:

  1. 输入一个使用“括号表示法”表示的二叉树,每个节点的数据为一个字符,请使用二叉链的存储方式构建二叉树B。
  2. 使用中序遍历法遍历构建的二叉树,输出中序遍历的序列。
  3. 输出该二叉树的高度(深度),其中,根节点作为第1层。
  4. 计算该二叉树中所有叶子节点的个数。
  5. 将该二叉树的左右子树进行交换,生成一个新的二叉树T。
  6. 将新生成的二叉树 T 使用括号表示法表示,并输出该括号表示法的结果。

输入格式:

输入一个不带空格的字符串,以换行结尾。

输出格式:

输入样例:

A(B(D(,G)),C(E,F))

结尾无空行

输出样例:

D G B A E C F 
4
3
A(C(F,E),B(,D(G)))

标签:10,Right,54,BT,二叉树,NULL,BinTree,Left
来源: https://blog.csdn.net/m0_63982781/article/details/121677320