二叉链表存储二叉树,递归算法先序、中序、后序输出所有节点,查找节点所在层次。

1.二叉树采用二叉链表存储,设计一个递归算法先序、中序、后序遍历顺序输出所有节点。

2.二叉树采用二叉链表存储,所有节点值均不相同,设计一个递归算法求值为x的节点所在层次。

#include <iostream>
#include <stdlib.h>
#include <malloc.h>
#include <string>
using namespace std;

typedef struct Node {	//定义结构体
	char data;
	struct Node* lchild;
	struct Node* rchild;
}BTnode, * BTtree;

void Initlist(BTtree* bt)	//初始化
{
	*bt = (BTtree)malloc(sizeof(BTnode));
	(*bt)->lchild = NULL;
	(*bt)->rchild = NULL;
}

void createBTtree(BTtree* bt)	//创建二叉树
{
	char c;
	c = getchar();
	if (c == ' ')
	{
		*bt = NULL;
	}
	else
	{
		*bt = (BTtree)malloc(sizeof(BTnode));
		(*bt)->data = c;
		createBTtree(&((*bt)->lchild));
		createBTtree(&((*bt)->rchild));
	}
}

void pretree(BTtree tree)	//前序
{
	if (tree == NULL)
		return;
	if (tree != NULL)
	{
		cout << tree->data;
		pretree(tree->lchild);
		pretree(tree->rchild);
	}
}

void inordertree(BTtree tree)	//中序
{
	if (tree == NULL)
		return;
	if (tree != NULL)
	{
		inordertree(tree->lchild);
		cout << tree->data;
		inordertree(tree->rchild);
	}
}

void postordertree(BTtree tree)	//后序
{
	if (tree == NULL)
		return;
	if (tree != NULL)
	{
		postordertree(tree->lchild);
		postordertree(tree->rchild);
		cout << tree->data;
	}
}

int level(BTnode* bt, int h, int x)	//查找x
{
	if (bt == NULL)
		return 0;
	if (bt->data == x)
		return h;
	else
	{
		int lh = level(bt->lchild, h + 1, x);
		if (lh != 0)
			return lh;
		else
			return level(bt->rchild, h + 1, x);
	}
	return 0;
}

void DestroyBTree(BTnode* bt)	//销毁
{
	if (bt == NULL)
		return;
	else
	{
		DestroyBTree(bt->lchild);
		DestroyBTree(bt->rchild);
		free(bt);
	}
}

int main()
{
	char x;
	int h = 0;
	BTtree bttree;
	Initlist(&bttree);
	cout << "输入二叉数的元素:" << endl;
	createBTtree(&bttree);
	cout << "先序遍历输出二叉树:" << endl;
	pretree(bttree);
	cout << endl;
	cout << "中序遍历输出二叉树:" << endl;
	inordertree(bttree);
	cout << endl;
	cout << "后序遍历输出二叉树:" << endl;
	postordertree(bttree);
	cout << endl << "输入要查询的元素:" << endl;
	cin >> x;
	cout << "所查询元素位于第" << level(bttree, h, x) << "层" << endl;
	DestroyBTree(bttree);
	system("pause");
	return 0;
}

运行结果

输入abd e cf g
在这里插入图片描述

二叉树图

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值