详细的二叉树的创建,销毁,遍历,完全二叉树判断代码实现

目录

一,设计数据结构,需要实现的接口

binar_tree.h

二,具体功能的实现

1.给定一个字符数组序列创建二叉树,其中#用来表示空指针

2.其销毁

3.二叉树的前中后序以及层次遍历

4.判断一个树是否为完全二叉树


一,设计数据结构,需要实现的接口

binar_tree.h

typedef struct BinaryTreeNode
{
	BTDataType _data;
	struct BinaryTreeNode* _left;
	struct BinaryTreeNode* _right;
}BTNode;

void BinaryTreeDestory(BTNode** root);

BTNode* BinaryTreeCreate(BTDataType* cur, int n, int* _i);

void BinaryTreePrevOrder(BTNode* root);

void BinaryTreeInOrder(BTNode* root);

void BinaryTreePostOrder(BTNode* root);

void BinaryTreeLevelOrder(BTNode* root);

int BinaryTreeComplete(BTNode* root);

二,具体功能的实现

1.给定一个字符数组序列创建二叉树,其中#用来表示空指针

BTNode* BinaryTreeCreate(BTDataType* cur, int n, int* _i)
{
	if (*_i >= n || cur[*_i] == '#')
	{
		(*_i)++;
		return NULL;
	}

	BTNode* _new = (BTNode*)malloc(sizeof(BTNode));
	_new->_data = cur[*_i];
	(*_i)++;

	_new->_left = BinaryTreeCreate(cur, n, _i);
	_new->_right = BinaryTreeCreate(cur, n, _i);

	return _new;
}

2.其销毁

void BinaryTreeDestory(BTNode** root)
{
	if (*root)
	{
		BinaryTreeDestory(&(*root)->_left);//因为销毁的时候传入的是二级指针,所以直接对*root取地址给这个二级指针;
		BinaryTreeDestory(&(*root)->_right);
		free(*root);
		*root = NULL;//这里传入二级指针的作用就是为了对根节点进行置空,不然没有必要。
	}
}

3.二叉树的前中后序以及层次遍历

void BinaryTreePrevOrder(BTNode* root)
{
	if (root)
	{
		putchar(root->_data);
		BinaryTreePrevOrder(root->_left);
		BinaryTreePrevOrder(root->_right);
	}
}

void BinaryTreeInOrder(BTNode* root)
{
	if (root)
	{
		BinaryTreeInOrder(root->_left);
		putchar(root->_data);
		BinaryTreeInOrder(root->_right);
	}
}

void BinaryTreePostOrder(BTNode* root)
{
	if (root)
	{
		BinaryTreePostOrder(root->_left);
		BinaryTreePostOrder(root->_right);
		putchar(root->_data);
	}
}



void BinaryTreeLevelOrder(BTNode* root)
{
	Queue qu;
	BTNode* cur;

	QueueInit(&qu);

	QueuePush(&qu, root);

	while (!QueueIsEmpty(&qu))
	{
		cur = QueueTop(&qu);

		putchar(cur->_data);

		if (cur->_left)
		{
			QueuePush(&qu, cur->_left);
		}

		if (cur->_right)
		{
			QueuePush(&qu, cur->_right);
		}

		QueuePop(&qu);
	}

	QueueDestory(&qu);
}

4.判断一个树是否为完全二叉树

判断一棵树是否为「完全二叉树」的方式为:对其进行层次遍历,若遇到一个空结点,则其后面的结点必须全为空结点,否则不是完全二叉树。

int BinaryTreeComplete(BTNode* root)
{
	Queue qu;
	BTNode* cur;
	int tag = 0;

	QueueInit(&qu);

	QueuePush(&qu, root);

	while (!QueueIsEmpty(&qu))对每一层每一个节点的左右节点进行检查,完全没有问题则检查下一个节点
	{
		cur = QueueTop(&qu);

		putchar(cur->_data);

		if (cur->_right && !cur->_left)
		{
			return 0;
		}

		if (tag && (cur->_right || cur->_left))
		{
			return 0;
		}

		if (cur->_left)
		{
			QueuePush(&qu, cur->_left);
		}

		if (cur->_right)
		{
			QueuePush(&qu, cur->_right);
		}
		else//当右边子树为空的时候,只要在后续层序遍历再能遍历到任何一个节点,那么它必然不是完全二叉树
		{
			tag = 1;
		}

		QueuePop(&qu);
	}

	QueueDestory(&qu);
	return 1;
}

猜你喜欢

转载自blog.csdn.net/m0_74234485/article/details/131583533