前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++编程之美-结构之法(代码清单3-11)

C++编程之美-结构之法(代码清单3-11)

作者头像
cwl_java
发布2022-11-30 08:52:50
1480
发布2022-11-30 08:52:50
举报
文章被收录于专栏:cwl_Java

代码清单3-11

代码语言:javascript
复制
// 数据结构定义
struct NODE
{
     NODE* pLeft;        	// 左子树
     NODE* pRight;      	// 右子树
     int nMaxLeft;      	// 左子树中的最长距离
     int nMaxRight;     	// 右子树中的最长距离
     char chValue;    	// 该节点的值
};

int nMaxLen = 0;

// 寻找树中最长的两段距离
void FindMaxLen(NODE* pRoot)
{
     // 遍历到叶子节点,返回
     if(pRoot == NULL)
     {
          return;
     }

     // 如果左子树为空,那么该节点的左边最长距离为0
     if(pRoot -> pLeft == NULL)
     {
          pRoot -> nMaxLeft = 0; 
     }

     // 如果右子树为空,那么该节点的右边最长距离为0
     if(pRoot -> pRight == NULL)
     {
          pRoot -> nMaxRight = 0;
     }

     // 如果左子树不为空,递归寻找左子树最长距离
     if(pRoot -> pLeft != NULL)
     {
          FindMaxLen(pRoot -> pLeft);
     }

     // 如果右子树不为空,递归寻找右子树最长距离
     if(pRoot -> pRight != NULL)
     {
          FindMaxLen(pRoot -> pRight);
     }

     // 计算左子树最长节点距离
     if(pRoot -> pLeft != NULL)
     {
          int nTempMax = 0;
          if(pRoot -> pLeft -> nMaxLeft > pRoot -> pLeft -> nMaxRight)
          {
               nTempMax = pRoot -> pLeft -> nMaxLeft;
          }
          else
          {
               nTempMax = pRoot -> pLeft -> nMaxRight;
          }
          pRoot -> nMaxLeft = nTempMax + 1;
     }

     // 计算右子树最长节点距离
     if(pRoot -> pRight != NULL)
     {
          int nTempMax = 0;
          if(pRoot -> pRight -> nMaxLeft > pRoot -> pRight -> nMaxRight)
          {
               nTempMax = pRoot -> pRight -> nMaxLeft;
          }
          else
          {
               nTempMax = pRoot -> pRight -> nMaxRight;
          }
          pRoot -> nMaxRight = nTempMax + 1;
     }

     // 更新最长距离
     if(pRoot -> nMaxLeft + pRoot -> nMaxRight > nMaxLen)
     {
          nMaxLen = pRoot -> nMaxLeft + pRoot -> nMaxRight;
     }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-01-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码清单3-11
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档