写一个程序求一棵二叉树中相距最远的两个节点之间的距离。
相距最远的两个节点,一定是两个叶子节点,或者是一个叶子节点到它的根节点。
代码一:
// 直接动态规划递归求解
struct NODE
{
NODE *lchild;
NODE *rchild;
int MaxLeft; // 左子树中的最长距离
int MaxRight; // 右子树中的最长距离
int data;
};
int MaxLen=0;
void FindMaxLen(NODE *pRoot) // 返回值为空
{
if(pRoot==NULL)
return;
if(pRoot->lchild==NULL)
pRoot->MaxLeft=0;
if(pRoot->rchild==NULL)
pRoot->MaxRight=0;
if(pRoot->lchild!=NULL) // 递归寻找根节点左孩子的最长距离 pRoot->lchild->MaxLeft
FindMaxLen(pRoot->lchild);
if(pRoot->rchild!=NULL) // 递归寻找根节点右孩子的最长距离 pRoot->rchild->MaxRight
FindMaxLen(pRoot->rchild);
if(pRoot->lchild!=NULL) // pRoot->MaxLeft
{
int TempMax=0;
if(pRoot->lchild->MaxLeft>pRoot->lchild->MaxRight)
TempMax=pRoot->lchild->MaxLeft;
else
TempMax=pRoot->lchild->MaxRight;
pRoot->MaxLeft=TempMax+1;
}
if(pRoot->rchild!=NULL) // pRoot->MaxRight
{
int TempMax=0;
if(pRoot->rchild->MaxLeft>pRoot->rchild->MaxRight)
TempMax=pRoot->rchild->MaxLeft;
else
TempMax=pRoot->rchild->MaxRight;
pRoot->MaxRight=TempMax+1;
}
// 更新最长距离 MaxLen
if(pRoot->MaxLeft+pRoot->MaxRight>MaxLen)
MaxLen=pRoot->MaxLeft+pRoot->MaxRight;
}
自己想的代码二,是基于树的深度,但思路上还是递归求解各个节点的MaxLen,基本用上题思路。
// 通过节点的深度求解
struct NODE
{
NODE *lchild;
NODE *rchild;
int data;
int currentLen; // 记录通过当前节点的二叉树节点的最大距离
};
int maxlen=0; // 记录最大距离
int Depth(NODE *pRoot) // 求二叉树的深度
{
if(pRoot==NULL)
return 0;
int depth=0;
int ldepth=Depth(pRoot->lchild);
int rdepth=Depth(pRoot->rchild);
depth=(ldepth>rdepth?ldepth:rdepth)+1;
return depth;
}
void FindMaxLen(NODE *pRoot) // 寻找最大距离
{
if(pRoot==NULL)
return;
else
{
int leftlen=(pRoot->lchild==NULL?0:Depth(pRoot->lchild)-1+1);
int rightlen=(pRoot->rchild==NULL?0:Depth(pRoot->rchild)-1+1);
pRoot->currentLen=leftdepth+rightdepth;
if(pRoot->currentLen>maxlen)
maxlen=pRoot->currentLen;
FindMaxLen(pRoot->lchild);
FindMaxLen(pRoot->rchild);
}
}