二叉樹的創建遍歷 遞歸實現

二叉樹的實現

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);
}



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