数据结构-链式二叉树的相关操作

typedef int BTDataType;

typedef struct BinaryTreeNode
{
	BTDataType data;
	struct BinaryTreeNode* left;
	struct BinaryTreeNode* right;
}BTNode;

BTNode* BuyNode(BTDataType x)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	if (node == NULL)
	{
		perror("malloc fail::");
		return;
	}
	node->data = x;
	node->left = NULL;
	node->right = NULL;
	return node;
}

BTNode* CreatBinaryTree()
{
	BTNode* node1 = BuyNode(1);
	BTNode* node2 = BuyNode(2);
	BTNode* node3 = BuyNode(3);
	BTNode* node4 = BuyNode(4);
	BTNode* node5 = BuyNode(5);
	BTNode* node6 = BuyNode(6);

	node1->left = node2;
	node1->right = node4;
	node2->left = node3;
	node4->left = node5;
	node4->right = node6;
	return node1;
}

//前序遍历链式二叉树
void PrevOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL  ");
		return;
	}
	printf("%d  ", root->data);
	PrevOrder(root->left);
	PrevOrder(root->right);
}

//中序遍历链式二叉树
void InOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL  ");
		return;
	}
	InOrder(root->left);
	printf("%d  ", root->data);
	InOrder(root->right);
}
//后续遍历链式二叉树
void PostOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL  ");
		return;
	}
	PostOrder(root->left);
	PostOrder(root->right);
	printf("%d  ", root->data);
}
//求链式二叉树结点的个数——方法一
int BTreeSize1(BTNode* root)
{
	if (root == NULL) return 0;
	else return BTreeSize1(root->left)+BTreeSize1(root->right)+1;
}
//求链式二叉树结点的个数——方法二
int size = 0;
void BTreeSize2(BTNode* root)
{
	if (root == NULL) return;
	else size++;
	BTreeSize2(root->left);
	BTreeSize2(root->right);
	return;
}
//求链式二叉树叶子结点的个数
int BTreeLeafSize(BTNode* root)
{
	if (root == NULL)
		return 0;
	else if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}
	else return BTreeLeafSize(root->left) + BTreeLeafSize(root->right);
}
//求链式二叉树的高度
//尽量不用分治的方法,因为分治方法时间复杂度较高,针对于较大的树不实用。
int BTreeHeight(BTNode* root)
{
	if (root == NULL)
		return 0;
	int leftHeight = BTreeHeight(root->left);
	int rightHeight = BTreeHeight(root->right);
	return leftHeight > rightHeight ?  leftHeight + 1: rightHeight + 1;
}
//求链式二叉树第k层的结点个数
int BTreeLevelSize(BTNode* root, int k)
{
	assert(k > 0);
	if (root == NULL)
		return 0;
	if (k == 1)
	{
		return 1;
	}
	else return BTreeLevelSize(root->left, k - 1) + BTreeLevelSize(root->right, k - 1);
}
int main() 
{
	/*HP hp;
	HeapInit(&hp);
	int a[] = { 1,3,7,2,6,19 };
	for (int i = 0; i < sizeof(a) / sizeof(int); ++i)
	{
		HeapPush(&hp, a[i]);
	}
	HeapSort(hp.a, hp.size);*/

	/*CreatNDate();
	PrintTopK(5);*/
	BTNode* root = CreatBinaryTree();
	/*PrevOrder(root);
	printf("\n");
	InOrder(root);
	printf("\n");
	PostOrder(root);
	printf("\n");*/
	BTreeSize2(root);
	printf("%d\n",size);
	size = 0;
	BTreeSize2(root);
	printf("%d\n", size);
	size = 0;
	BTreeSize2(root);
	printf("%d\n", size);
	printf("%d\n", BTreeLevelSize(root,3));
	printf("%d\n", BTreeLevelSize(root,2));
	printf("%d\n", BTreeLevelSize(root,1));
	return 0;
}

你可能感兴趣的:(数据结构,c++)