1. 程式人生 > >【資料結構週週練】013 利用棧和非遞迴演算法求二叉樹的高

【資料結構週週練】013 利用棧和非遞迴演算法求二叉樹的高

一、前言

二叉樹的高是樹比較重要的一個概念,指的是樹中結點的最大層數本次演算法通過非遞迴演算法來求得樹的高度,借用棧來實現樹中結點的儲存。

學英語真的很重要,所以文中的註釋還有輸出以後會盡量用英語寫,文中出現的英語語法或者單詞使用錯誤,還希望各位英語大神能不吝賜教。

二、題目

將下圖用二叉樹存入,並求樹的高度。其中圓角矩形內為結點資料,旁邊數字為結點編號,編號為0的結點為根節點,箭頭指向的結點為箭尾的孩子結點。

 

 三、程式碼

#define MAXQUEUESIZE 10

#include<iostream>
#include<malloc.h>

using namespace std;

typedef struct BiTNode {
	int data;
	int number;
	struct BiTNode *lChild, *rChild, *parent;
}BiTNode, *BiTree;

typedef BiTree SElemType;

typedef struct LNode{
	SElemType data;
	int high;
	struct LNode *next;
}LNode,*LinkStack;

int number = 0;
int yon = 0;
int yesOrNo[] = { 1,0,1,0,0,1,1,1,0,0,1,0,0,1,0,0 };
int numData[] = { 1,2,4,3,5,7,8,6 };
BiTree treeParent = NULL;

int InitStack(LinkStack &S) {
	S = (LinkStack)malloc(sizeof(LNode));
	if (!S) {
		cout << "空間分配失敗(Allocate space failure)" << endl;
		exit(OVERFLOW);
	}
	S->high = 0;
	S->next = NULL;
	return 1;
}

int Push(LinkStack &S, SElemType e) {
	LinkStack p = (LinkStack)malloc(sizeof(LNode));
	if (!p)
	{
		cout << "結點分配失敗(Allocate node failure)" << endl;
		exit(OVERFLOW);
	}
	S->data = e;
	p->next = S;
	p->high = S->high;
	S = p;
	S->high += 1;
	return 1;
}

int Pop(LinkStack &S, SElemType &e) {
	LinkStack p = S->next;
	if (!p)
	{
		cout << "棧空(The stack is null)" << endl;
		exit(OVERFLOW);
	}
	e = p->data;
	S->next = p->next;
	free(p);
	S->high -= 1;
	return 1;
}

// Operation of the tree
int OperationBiTree(BiTree &T) {
	T = (BiTree)malloc(sizeof(BiTNode));
	if (!T)
	{
		cout << "空間分配失敗" << endl;
		exit(OVERFLOW);
	}
	T->number = number;
	number++;
	T->data = numData[T->number];
	T->lChild = NULL;
	T->rChild = NULL;
	T->parent = treeParent;
	return 1;
}

//establish the tree, utilize recursion
void EstablishBiTree(BiTree &T) {
	OperationBiTree(T);
	treeParent = T;
	if (yesOrNo[yon++])
		EstablishBiTree(T->lChild);
	treeParent = T;
	if (yesOrNo[yon++])
		EstablishBiTree(T->rChild);
}


//Seek high of the tree
int BiTreeHigh(BiTree T) {
	BiTree p = T;
	LinkStack S;
	int high = 0;
	InitStack(S);
	while (p||S->next)
	{
		if (p) {
			Push(S, p);
			p = p->lChild;
			if (high<S->high)
				high = S->high;
		}
		else
		{
			Pop(S, p);
			p = p->rChild;
		}
	}
	return ++high;
}

void VisitBiTree(BiTree T) {
	cout << "The number of present node is :" << T->number << "; ";
	cout << "data is :" << T->data << "; ";
	if (!T->parent)
		cout << " this node is the root of the tree.\n";
	if (!T->lChild && !T->rChild)
		cout << " this node is the leaf of the tree.\n";
	cout << endl;
	
}

//Visit tree use the preorder technique. 
void PreOrderBiTree(BiTree T) {
	if (T)
	{
		VisitBiTree(T);
		PreOrderBiTree(T->lChild);
		PreOrderBiTree(T->rChild);
	}
}

void main() {
	BiTree T;
	EstablishBiTree(T);
	PreOrderBiTree(T);
	cout << "The high of tree which we establish is " << BiTreeHigh(T) << endl;
}

四、實現效果