分析详见《编程之美》
code
#include <stdio.h>
#include <stdlib.h>
#define A 17
int s[A]={10,6,4,-1,-1,8,-1,-1,14,12,-1,18,-1,-1,16,-1,-1};
int index=0;
int maxlen=0;
typedef struct TREE_NODE
{
int data;
struct TREE_NODE* ltree;
struct TREE_NODE* rtree;
int lmaxlen;
int rmaxlen;
}NODE;
NODE* newnode()
{
NODE* temp;
temp=(NODE*)malloc(sizeof(NODE));
return temp;
}
void constructtree(NODE* &pnode)
{
if(s[index]!=-1)
{
pnode=newnode();
pnode->data=s[index++];
constructtree(pnode->ltree);
constructtree(pnode->rtree);
}
else
{
pnode=NULL;
index++;
}
}
/**
基本思想:
先序递归,递归到叶子节点后回溯计算
*/
void searchmaxlen(NODE* pnode)
{
if(pnode->ltree==NULL)
{
pnode->lmaxlen=0;
}
if(pnode->rmaxlen==NULL)
{
pnode->rmaxlen=0;
}
if(pnode->ltree!=NULL)
{
searchmaxlen(pnode->ltree);
}
if(pnode->rtree!=NULL)
{
searchmaxlen(pnode->rtree);
}
int temp;
if(pnode->ltree!=NULL)
{
if(pnode->ltree->lmaxlen>pnode->ltree->rmaxlen)
{
temp=pnode->ltree->lmaxlen;
}
else
{
temp=pnode->ltree->rmaxlen;
}
pnode->lmaxlen=temp+1;
}
if(pnode->rtree!=NULL)
{
if(pnode->rtree->lmaxlen>pnode->rtree->rmaxlen)
{
temp=pnode->rtree->lmaxlen;
}
else
{
temp=pnode->rtree->rmaxlen;
}
pnode->rmaxlen=temp+1;
}
if(pnode->lmaxlen+pnode->rmaxlen>maxlen)
{
maxlen=pnode->lmaxlen+pnode->rmaxlen;
}
}
int main(void)
{
NODE* root;
constructtree(root);
searchmaxlen(root);
printf("The max distance of the tree is %d.\n",maxlen);
system("pause");
return 0;
}