第十一题:求二叉树任意两结点的最大距离

#include "bst.h"
#include <stdlib.h>
#include <stdio.h>
#define max(a,b) ((a)>(b) ? (a) : (b))
/*
 ============================================================================
 求二叉树中任意两点的最大距离
 ============================================================================
 思想:有三种可能:
 	 (1)左子树中结点的最大距离
 	 (2)右子树中结点的最大距离
 	 (3)左子树的深度+右子树的深度
 	 其中最大的就是所求。OK,递归。
 */
int getMaxDistance(Node* head,int &depth)
{
	if(head==NULL)
	{
		depth=0;
		return 0;
	}
	int ld,rd,maxLeft,maxRight;
	maxLeft=getMaxDistance(head->pLeft,ld);
	maxRight=getMaxDistance(head->pRight,rd);
	depth=max(ld,rd)+1;
	return max(maxLeft,max(maxRight,ld+rd));
}
int main()
{
	int s[]={234,34,24,4,34,2,3,6,67,34,255,266,280};
	int len=sizeof(s)/sizeof(int);
	Node* head=createList(s,len);
	int depth;
	printf("distance:%d\n",getMaxDistance(head,depth));
	pr_midOrder(head);
	free_afterOrder(head);
	getchar();
	return 0;
}
其中头文件为
#ifndef BST_H_
#define BST_H_
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
	int data;
	struct node* pLeft;
	struct node* pRight;
} Node;
//中序插入
Node* insertList(int m, Node *pRoot)
{
	Node* pTmp;
	pTmp = (Node*) malloc(sizeof(Node));
	pTmp->data = m;
	pTmp->pLeft = NULL;
	pTmp->pRight = NULL;
	if (pRoot == NULL)
	{
		return pTmp;
	}
	else
	{
		if (m < pRoot->data)
		{
			if (pRoot->pLeft == NULL)
				pRoot->pLeft = pTmp;
			else
				insertList(m, pRoot->pLeft);
		}
		else
		{
			if (pRoot->pRight == NULL)
				pRoot->pRight = pTmp;
			else
				insertList(m, pRoot->pRight);
		}

	}
	return pRoot;
}

Node* createList(int a[], int n)
{
	int i = 0;
	Node* pNode = NULL;
	for (i = 0; i < n; i++)
	{
		pNode = insertList(a[i], pNode);
	}
	return pNode;
}
//中序遍历
void pr_midOrder(Node* pNode)
{
	if (pNode == NULL)
		return;
	pr_midOrder(pNode->pLeft);
	printf(" %d", pNode->data);
	pr_midOrder(pNode->pRight);
}
//后序释放
void free_afterOrder(Node *pNode)
{
	if (pNode == NULL)
		return;
	if (pNode->pLeft == NULL && pNode->pRight == NULL)
	{
		free(pNode);
		return;
	}
	free_afterOrder(pNode->pLeft);
	free_afterOrder(pNode->pRight);
	free(pNode);

}


#endif /* BST_H_ */

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值