1. 程式人生 > >資料結構上機題(10.24)

資料結構上機題(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,到這就結束了,總之歡迎諸位捧場!