【CareerCup】Trees and Graphs—Q4.3

本文介绍了一种从有序数组构建最小高度二叉树的方法。通过选取数组中间元素作为根节点,递归地构建左右子树,确保了二叉树的高度最小。文中提供了完整的C语言实现代码,并展示了如何计算树的高度及进行中序遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明出处:http://blog.youkuaiyun.com/ns_code/article/details/24744177


    题目:

    Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.

    翻译:

    给定一个有序数组(递增),写程序构建一棵具有最小高度的二叉树。

    思路:

    要使二叉树的高度最小,则要尽量使其左右子树的节点数目相当,自然就考虑到将其构造成为二叉排序树,且将有序数组的中间大的数作为根节点,这样得到的二叉树的高度便是最小的。

    实现代码:

#include<stdio.h>
#include<stdlib.h>
typedef struct BTNode
{
	int data;
	struct BTNode *pLchild;
	struct BTNode *pRchild;
}BTNode, *BTree;

/*
根据给定的递增数组递归创建高度最小的二叉树,
因为要修改指向根节点的指针的指向,因此要传入pTree的指针,即BTNode的二级指针
*/
void createBTree(BTree *ppTree,int *A,int start,int end)
{
	if(start <= end)
	{
		int mid = (start + end)/2;
		*ppTree = (BTree)malloc(sizeof(BTNode));
		if(*ppTree == NULL)
		{
			printf("malloc faild");
			exit(EXIT_FAILURE);
		}
		(*ppTree)->data = A[mid];
		(*ppTree)->pLchild = NULL;
		(*ppTree)->pRchild = NULL;
		createBTree(&(*ppTree)->pLchild,A,start,mid-1);
		createBTree(&(*ppTree)->pRchild,A,mid+1,end);
	}
}

/*
返回两个整数的最大值
*/
int max(int a,int b)
{
	return a>b?a:b;
}

/*
求二叉树的深度
*/
int height(BTree pTree)
{
	if(pTree == NULL)
		return 0;
	else
		return max(height(pTree->pLchild),height(pTree->pRchild)) + 1;
}

/*
中序遍历的递归实现
*/
void in_traverse(BTree pTree)
{
	if(pTree)
	{
		if(pTree->pLchild)
			in_traverse(pTree->pLchild);
		printf("%d ",pTree->data);
		if(pTree->pRchild)
			in_traverse(pTree->pRchild);	
	}
}

int main()
{
	int A[] = {0,1,2,3,4,5,6,7};
	int len = 8;
	BTree pTree;
	createBTree(&pTree,A,0,len-1);
	printf("the height of this tree is %d\n",height(pTree));
	printf("中序遍历后的结果为:\n");
	in_traverse(pTree);
	printf("\n");
	return 0;
}

    测试结果:


    注:代码开源到Github:https://github.com/mmc-maodun/CareerCup


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值