编程之美3.8求二叉树中节点的最大距离

今天看了这道题,感觉作者的解法空间消耗太大,所以想出以下解决方案,由于代码本身比较简单所以我就不解释了,请看代码:

#include<stdio.h>
#include<stdlib.h>
typedef struct Node* link;
struct Node{
	link left;
	link right;
	int key;
};
static link head;
link NEW(link left, link right, int key)
{
	link templink = (link)malloc(sizeof(struct Node));
	templink->left = left;
	templink->right = right;
	templink->key = key;
}
link InsertToBinaryTree(link h,int key)
{
	if (NULL == h) return NEW(NULL, NULL, key);
	if (h->key > key)
		h->left = InsertToBinaryTree(h->left, key);
	else {
		h->right = InsertToBinaryTree(h->right, key);
	}
	return h;
}
int getMAXLengthBetweenTwoNodes(link h, int *MAXLength)
{
	int Lheight = 0;
	int Rheight = 0;
	if (NULL == h) return -1;
	Lheight = getMAXLengthBetweenTwoNodes(h ->left, MAXLength);
	Rheight = getMAXLengthBetweenTwoNodes(h ->right, MAXLength);
	if (Lheight + Rheight + 2 > *MAXLength)
		*MAXLength = Lheight + Rheight + 2;
	return (Lheight > Rheight ? Lheight : Rheight) + 1;
}
int GetMAXLengthBetweenTwoNodes(link head)
{
	if (NULL == head) return -1;
	int MAXLength = 0;
	getMAXLengthBetweenTwoNodes(head, &MAXLength);
	return MAXLength;
}
void main()
{
	int data[] = {6, 7, 8, 3, 4, 5, 6, 9};
	int i = 0;
        //创建BST
        for (i = 0; i < sizeof(data) / sizeof(data[0]); ++ i)
		head = InsertToBinaryTree(head, data[i]);
        //计算最大距离
        printf("MAXLENGTH = %d\n", GetMAXLengthBetweenTwoNodes(head));//测试结果:6
}


*最后发现跟这个博客的思想一样: http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值