标签:flush ret 相等 一个 create crt evel return void
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdlib.h>
#include <malloc.h>
using namespace std;
/*
BinaryTree结构体定义
*/
typedef struct BinaryTree
{
	char Data;
	struct BinaryTree* Left;
	struct BinaryTree* Right;
}BT,*PBT;
/*
函数定义	
*/
void CreateTree(PBT*);//创建二叉树
void PreOrder(PBT);//前序遍历
void MidOrder(PBT);//中序遍历
void PostOrder(PBT);//后序遍历
int FindLevel(PBT,char,int);//后序查找
/*
函数实现
*/
//创建二叉树
void CreateTree(PBT* root)//二级指针
{
	char temp;
	cin >> temp;
	if (temp == ‘!‘)
	{
		(*root) = NULL; //结点指针置空
	}
	else
	{
		(*root) = (PBT)malloc(sizeof(BT));//创建一个结点
		(*root)->Data = temp;//赋值
		//fflush(stdin);//清空缓冲
	    CreateTree(&((*root)->Left));//传一个二级指针进去,利用递归回溯来创建二叉树
		CreateTree(&((*root)->Right));
	}
	return;
}
//前序遍历
void PreOrder(PBT root)
{
	if (root != NULL)//指针不空
	{
		printf("%c\n", root->Data);//前序遍历就是先输出,再判断左,最后右,利用递归回溯可以实现
		PreOrder(root->Left);
		PreOrder(root->Right);
	}
}
//中序遍历
void MidOrder(PBT root)
{
	if (root != NULL)//指针不空
	{
		MidOrder(root->Left);
		printf("%c\n", root->Data);//中序遍历就是先遍历左,再输出根节点,最后右,利用递归回溯可以实现
		MidOrder(root->Right);
	}
}
//后序遍历
void PostOrder(PBT root)
{
	if (root != NULL)//指针不空
	{
		PostOrder(root->Left);
		PostOrder(root->Right);
		printf("%c\n", root->Data);//后序遍历就是左,再判断右,最后根输出,利用递归回溯可以实现
	}
}
//求层数
int FindLevel(PBT root, char x,int h)
{
	int level = 0;//默认高度为一,level为层数
	if (root == NULL)
	{
		return 0;//为空,递归回溯
		
	}
	if (root->Data == x)
	{
		return h;//数据相等,返回层数
	}
	else
	{
		level = FindLevel(root->Left, x,h + 1);//先遍历左子树
		
		if (level != 0) //不为零,说明数据找到了,不继续递归,回溯
			return level;//返回找到的层数,回溯
		else
		{
			level = FindLevel(root->Right, x, h + 1);//能到这一步,说明左子树没有找到,右子数继续
			return level;//返回
		}
	}
}
int main(void)
{
	char temp;
	PBT root;//创建一个二叉树指针
	CreateTree(&root);//递归创建二叉树
	printf("%s\n", "前序遍历");
	PreOrder(root);//前序遍历
	printf("%s\n", "中序遍历");
	MidOrder(root);//中序遍历
	printf("%s\n", "后序遍历");
	PostOrder(root);//后序遍历
	printf("%s\n", "输入你要查找的结点:");
	cin >> temp;
	int level = FindLevel(root, temp, 1);
	printf("%s%d\n","你查找的结点层数为:",level);
	
	return 0;
}
标签:flush ret 相等 一个 create crt evel return void
原文地址:https://www.cnblogs.com/rainpeaks/p/12907805.html