1. 程式人生 > >【資料結構週週練】015 利用遞迴演算法建立鏈式儲存的二叉樹並轉換左右孩子結點

【資料結構週週練】015 利用遞迴演算法建立鏈式儲存的二叉樹並轉換左右孩子結點

一、前言

哈哈,今天就是程式設計師節啦,祝大家1024程式設計師節快樂

今天要給大家分享的演算法是交換二叉樹是的左右孩子結點,比較簡單,需要建立一個結點用來暫存左孩子結點,下面給大家送上程式碼。

二、題目

將下圖用二叉樹存入,並交換二叉樹是的左右孩子結點。其中圓角矩形內為結點資料,旁邊數字為結點編號,編號為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;

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 OperationBiTree(BiTree &T) {
	T = (BiTree)malloc(sizeof(BiTNode));
	if (!T)
	{
		cout << "空間分配失敗(Allocate space failure.)" << endl;
		exit(OVERFLOW);
	}
	T->data = numData[number];
	T->number = number;
	number++;
	T->lChild = NULL;
	T->rChild = NULL;
	T->parent = treeParent;
	return 1;
}

int RecursionEstablishBiTree(BiTree &T) {
	OperationBiTree(T);
	treeParent = T;
	if (yesOrNo[yon++])
		RecursionEstablishBiTree(T->lChild);
	treeParent = T;
	if (yesOrNo[yon++])
		RecursionEstablishBiTree(T->rChild);

	return 1;
}

void VisitBiTree(BiTree &T) {
	cout << "The number of present node is :" << T->number << "; ";
	cout << "   data is :" << T->data << ";\n ";
	if (T->lChild)
		cout << "    has left child and the number is :" << T->lChild->number << ";\n";
	if (T->rChild)
		cout << "    has right child,and the number is :" << T->rChild->number << ";\n";
	cout << endl;
}

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

int ExchangeChildNode(BiTree &T) {
	BiTree p;
	if (T)
	{
		ExchangeChildNode(T->lChild);
		ExchangeChildNode(T->rChild);

		p = T->lChild;
		T->lChild = T->rChild;
		T->rChild = p;
	}
	return 1;
}

void main() {
	BiTree T;
	RecursionEstablishBiTree(T);

	cout << "************【Recursion of the binary tree just establish】************\n";
	PreOrderVisitBiTree(T);

	ExchangeChildNode(T);
	cout << "*******【Recursion of the binary tree just exchange child node】*******\n";
	PreOrderVisitBiTree(T);

}

四、實現效果

建立效果如下,遍歷訪問測試:

建立成功的二叉樹遍歷
第一棵樹

對於第二顆樹,只需要修改兩個位置,樹建立時候的兩個陣列:

int yesOrNo[] = { 1,1,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0 };
int numData[] = { 1,2,4,8,9,5,3,6,7 };

結果如下:

建立成功的二叉樹遍歷
第二棵樹