数据结构上机题(10.24)

10.24号周三的上机题,先别急,源代码在后面呢!!!

首先附上三张图,是关于什么是二叉树的先序遍历,中序遍历,后序遍历。

(1)先序遍历

按照“根节点,左支,右支”的顺序遍历,如图:

(2)中序遍历

按照“左支,根节点,右支”的顺序遍历,如图:

(2)后序遍历

按照“左支,右支,根节点”的顺序遍历,如图:

接着,交代一下大致的上机题内容:

实现创建一棵二叉树,计算树叶数,计算树的深度,计算结点数,计算分枝数。

原代码如下:

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

typedef struct bitnode
{
	char data;
	bitnode *lchild, *rchild;
}bitnode;

class bitt
{
	bitnode *pt;
	void create(bitnode *&t);
	void inorder(bitnode *t);
	int countleaf(bitnode *t);
	int deepth(bitnode *t);
	int countnode(bitnode *t);
	int countFZ(bitnode *t);
public:
	void createbitt() { bitnode *t; create(t); pt = t; }
	void inorderbitt() { bitnode *t = pt; inorder(t); }
	int countleafbitt() { bitnode *t = pt; return countleaf(t); }
	int deepthbitt() { bitnode *t = pt; return deepth(t); }
	int countnodebitt() { bitnode *t = pt; return countnode(t); }
	int countFZbitt() { bitnode *t = pt; return countFZ(t); }
};

void bitt::create(bitnode *&t)
{
	char ch;
	cin >> ch;
	if (ch == '.') t = NULL;
	else
	{
		t = new bitnode;
		t->data = ch;
		create(t->lchild);
		create(t->rchild);
	}
}

void bitt::inorder(bitnode *t)
{
	if (t)
	{
		inorder(t->lchild);
		cout << t->data;
		inorder(t->rchild);
	}
}

int bitt::countleaf(bitnode *t)
{
	if (t == NULL) return 0;
	else
	{
		int m = countleaf(t->lchild);
		int n = countleaf(t->rchild);
		if (m + n == 0) return 1;
		else return m + n;
	}
}

int bitt::deepth(bitnode *t)
{
	if (t == NULL) return 0;
	else
	{
		int m = 1 + deepth(t->lchild);
		int n = 1 + deepth(t->rchild);
		if (m >= n) return m;
		else return n;
	}
}

int bitt::countnode(bitnode *t)
{
	if (t == NULL) return 0;
	else
	{
		int m = countnode(t->lchild);
		int n = countnode(t->rchild);
		return m + n + 1;
	}
}

int bitt::countFZ(bitnode *t)
{
	int a = countnode(t);
	int b = countleaf(t);
	return a - b;
}

int main(void)
{
	bitt tt;
	cout << "输入一棵树:" << endl;
	tt.createbitt();
	cout << "中序遍历输出该树:";
	tt.inorderbitt();
	cout << endl;
	cout << "该树的树叶数:";
	cout << tt.countleafbitt()<<endl;
	cout << "该树的深度:";
	cout << tt.deepthbitt() << endl;
	cout << "该树的结点数:";
	cout << tt.countnodebitt() << endl;
	cout << "该树的分枝数:";
	cout << tt.countFZbitt() << endl;
	cout << "OVER" << endl;
	system("pause");
	return 0;
}

下面是运行结果的截图:

输入的树的拓扑图是这样的:

画的有点丑QAQ,不要介意哦qwq,到这就结束了,总之欢迎诸位捧场!

猜你喜欢

转载自blog.csdn.net/qq_41938259/article/details/83187174