第三章 -- 求二叉树中节点的最大距离

写一个程序求一棵二叉树中相距最远的两个节点之间的距离。


相距最远的两个节点,一定是两个叶子节点,或者是一个叶子节点到它的根节点。

代码一:
//  直接动态规划递归求解

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); 
     } 
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值