学习二叉树

二叉树

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//二叉树
//用二叉链表表示

//二叉链表节点
typedef struct BiTNode
{
	int data;
	struct BiTNode *leftChild, *rightChild;
}BiTNode, *BiTree;


//先根遍历
void preOrder(BiTNode *node)
{
	if (node)
	{
		printf("%d ", node->data);
		preOrder(node->leftChild);
		preOrder(node->rightChild);
	}
}

//中根遍历
void centerOrder(BiTNode *node)
{
	if (node)
	{
		centerOrder(node->leftChild);
		printf("%d ", node->data);
		centerOrder(node->rightChild);
	}
}

//后根遍历
void footerOrder(BiTNode *node)
{
	if (node)
	{
		footerOrder(node->leftChild);
		footerOrder(node->rightChild);
		printf("%d ", node->data);
	}
}

int main(int argc, char* argv[])
{
	BiTNode b1, b2, b3, b4, b5;
	//初始化节点data及leftChild和rightChild 指针为NULL
	memset(&b1, 0, sizeof(BiTNode));
	memset(&b2, 0, sizeof(BiTNode));
	memset(&b3, 0, sizeof(BiTNode));
	memset(&b4, 0, sizeof(BiTNode));
	memset(&b5, 0, sizeof(BiTNode));

	//设置节点的值
	b1.data = 1;
	b2.data = 2;
	b3.data = 3;
	b4.data = 4;
	b5.data = 5;

	//构建关系
	b1.leftChild = &b2;
	b1.rightChild = &b3;
	b2.leftChild = &b4;
	b2.rightChild = &b5;

	printf("先根遍历:");
	preOrder(&b1);

	printf("\n中根遍历:");
	centerOrder(&b1);

	printf("\n后根遍历:");
	footerOrder(&b1);
	return 0;
}

编译和效果

gcc twotree.c -o twotree.exe -fexec-charset=gbk    #fexec-charset指定执行使用gbk

使用递归遍历二叉树,顺序为先根遍历/中根遍历及后跟遍历

秋风 2018-04-23