11.求二叉树中节点的最大距离

题目:

求二叉树中节点的最大距离...
如果我们把二叉树看成一个图,
父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
求一棵二叉树中相距最远的两个节点之间的距离。

答案:

//20130109
#include <iostream>
#include <ctime>
#include <list>
using namespace std;
typedef struct TNode 
{
	int num;
	TNode* lnode;
	TNode* rnode;
}TNode,*ptnode;
//逐层遍历序列,0代表空
/*树的机构
                 1
            2          3
          4     5     6   7
        0  0  0  8   0 0 0 0       
			   9   0
		      0 10
*/
int t1[]={1,2,3,4,5,6,7,0,0,0,8,0,0,0,0,9,0,0,10,0,0};
int t2[]={1,2,3,4,5,6,7,8,0,0,0,0,9,0,0,0,0,0,0};
TNode* constructTree(int tt[]);
int judge(ptnode  const node);

int maxs=-1;
int main()
{
	ptnode pnode=constructTree(t1);
	judge(pnode);
	cout<<maxs<<endl;
	return 0;
}
TNode* constructTree(int tt[])
{
	TNode *tn=new TNode;
	tn->num=tt[0];
	tn->lnode=NULL;
	tn->rnode=NULL;

	list<ptnode> tnl;
	tnl.push_back(tn);

	ptnode pnode;
	int num=1;
	while (!tnl.empty())
	{
		if (tt[num]!=0)
		{
			pnode=*(tnl.begin());
			TNode *tns=new TNode;
			tns->num=tt[num];
			tns->lnode=NULL;
			tns->rnode=NULL;
			pnode->lnode=tns;
			tnl.push_back(tns);
		}
		if (tt[num+1]!=0)
		{
			pnode=*(tnl.begin());
			TNode *tns=new TNode;
			tns->num=tt[num+1];
			tns->lnode=NULL;
			tns->rnode=NULL;
			pnode->rnode=tns;
			tnl.push_back(tns);
		}
		num=num+2;
		tnl.pop_front();
	}
	return tn;
}

int judge(ptnode  const node)
{
	if (node==NULL)
	{
		return -1;
	}
	int a=judge(node->lnode)+1;
	int b=judge(node->rnode)+1;
	if (a+b>maxs)
	{
		maxs=a+b;
	}
	return a>b?a:b;
}


参考文章: http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值