题目:
求二叉树中节点的最大距离...
如果我们把二叉树看成一个图,
父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
求一棵二叉树中相距最远的两个节点之间的距离。
答案:
//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;
}