1. 程式人生 > >資料結構進階——二叉樹,紅黑樹

資料結構進階——二叉樹,紅黑樹

基本定義:一個根節點下分兩個子節點的樹結構稱為二叉樹。A為根節點,B、C分別為左孩子和右孩子,E這種無孩子的結點成為葉子結點,A,B,D,G共4層。二叉樹存在的三種排序方式圖中也說明的很清晰了。

先序:根->左->右;

中序:左->根->右;

後序:左->右->根;

#include <stdio.h>

typedef struct TREE {
	struct TREE* leftChild;
	struct TREE* rightChild;
	void* value;
}TREE;

void init(TREE** root, void* data);
void clear(TREE** root);
void makeLeftChild(TREE* root, void* data);
void makeRightChild(TREE* root, void* data);
void showTreeByFirst(TREE* root);
void showTreeBySecond(TREE* root);
void showTreeByThird(TREE* root);

void init(TREE** root, void* data) {
	TREE** head;
	TREE* tmp;
	if (NULL == root || NULL != *root) {
		printf("Wrong input init value!\n");
		return;
	}

	head = root;
	(*head) = (TREE*) calloc(sizeof(TREE), 1);
	// test
	*root = *head;
	tmp = *head;
	(tmp->value) = data;
	tmp->leftChild = NULL;
	tmp->rightChild = NULL;

	printf("data = %d\n", *(int *)data);
}

void clear(TREE** root) {
	TREE* tmp = *root;
	static int times = 0;

	if(tmp->leftChild != NULL) {
		clear(&(tmp->leftChild));
		printf("Left clear!\n");
		
	}
	if(tmp->rightChild != NULL) {
		clear(&(tmp->rightChild));
		printf("Right clear!\n");
	}
	free(tmp);
	*root = NULL;

	printf("Clear complete! time = %d\n", ++times);
}

void makeLeftChild(TREE* root, void* data) {
	TREE* left = NULL;
	init(&left, data);
	root->leftChild = left;

	printf("Make LeftChild complete! leftData = %d\n", *((int *)data));
}

void makeRightChild(TREE* root, void* data) {
	TREE* right = NULL;
	init(&right, data);
	root->rightChild = right;

	printf("Make rightChild complete! rightData = %d\n", *((int *)data));
}

void showTreeByFirst(TREE* root) {
	if(root != NULL) {
		printf("root->value = %d\n", *((int *)root->value));
		showTreeByFirst(root->leftChild);
		showTreeByFirst(root->rightChild);

		if(*((int *)root->value) == 1) {
			printf("First Show over!\n");
		}
	}
}

void showTreeBySecond(TREE* root) {
	if(root != NULL) {
		showTreeBySecond(root->leftChild);
		printf("root->value = %d\n", *((int *)root->value));
		showTreeBySecond(root->rightChild);

		if(*((int *)root->value) == 1) {
			printf("Second Show over!\n");
		}
	}
}

void showTreeByThird(TREE* root) {
	if(root != NULL) {
		showTreeByThird(root->leftChild);
		showTreeByThird(root->rightChild);
		printf("root->value = %d\n", *((int *)root->value));

		if(*((int *)root->value) == 1) {
			printf("Third Show over!\n");
		}
	}
}

void main(void) {
	TREE* root = NULL;
	int data = 1;
	int leftData = 2;
	int rightData = 3;
	int leftleftData = 4;
	int leftrightData = 5;

	init(&root, &data);
	makeLeftChild(root, &leftData);
	makeLeftChild(root->leftChild, &leftleftData);
	makeRightChild(root->leftChild, &leftrightData);
	makeRightChild(root, &rightData);

	showTreeByFirst(root);
	showTreeBySecond(root);
	printf("\n");
	showTreeByThird(root);
	printf("\n");
	clear(&root);

	printf("%d\n", root);
}