二叉树的创建遍历 递归实现

二叉树的实现

1> 二叉树的创建, 先序创建二叉树

2>二叉树的销毁

3>二叉树先序遍历打印

4>二叉树中序遍历打印

5>二叉树后续遍历打印

6>求二叉树高度(深度)

7>求二叉树节点个数


#include <iostream>

enum Status{OK, ERROR, OVERDATA};

typedef char DataType;
typedef struct BinaryNode
{
	DataType  data;
	BinaryNode* lTree;
	BinaryNode* rTree;
}BinNode, *BinTree;

// 先序创建二叉树
BinTree  PreCreateBinaryTree()
{
    DataType elem;
	elem = getchar();

	if (elem == '#')
		return NULL;

	BinNode* node = (BinNode*) malloc(sizeof(BinNode));
	if (NULL == node)
	{
		std::cout << "the malloc failed for node." << std::endl;
		exit(0);
	}

	node->data = elem;
	node->lTree = PreCreateBinaryTree();
	node->rTree = PreCreateBinaryTree();
	return node;
}

// 销毁二叉树
void destoryTree(BinTree tree)
{
	if (NULL  ==  tree)
		return ;
	destoryTree(tree->lTree);
	destoryTree(tree->rTree);
	free(tree);
	tree = NULL;
}

// 先序打印二叉树
void PrePrintBinaryTree(BinTree tree)
{
	if (NULL == tree) return;
	std::cout << " " << tree->data;
	PrePrintBinaryTree(tree->lTree);
	PrePrintBinaryTree(tree->rTree);
}

// 中序遍历打印二叉树
void InPrintBinaryTree(BinTree tree)
{
	if (NULL == tree)
		return;

	InPrintBinaryTree(tree->lTree);
	std::cout << " " << tree->data;
	InPrintBinaryTree(tree->rTree);
}

// 后序遍历打印二叉树
void PostPrintBinaryTree(BinTree tree)
{
	if (NULL == tree)
		return;

	PostPrintBinaryTree(tree->lTree);
	PostPrintBinaryTree(tree->rTree);
	std::cout << " " << tree->data;
}

// 求二叉树的高度
int TreeHigh(BinTree tree)
{
	if (NULL == tree)
		return 0;
	int lh = TreeHigh(tree->lTree);
	int rh = TreeHigh(tree->rTree);

	return 1 + (lh > rh ? lh : rh);
}

// 求二叉树的结点个数
int NodeCount(BinTree tree)
{
	if (NULL == tree)
		return 0;

	return 1 + NodeCount(tree->lTree) + NodeCount(tree->rTree);
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章