二叉树中最远两个节点的距离

来源:互联网 发布:客餐厅装饰画淘宝网 编辑:程序博客网 时间:2024/05/21 10:21

计算一个二叉树的最大距离有两个情况:

情况1: 路径经过左子树的最深节点,通过根节点,再到右子树的最深节点。

情况2: 路径不穿过根节点,而是左子树或右子树的最大距离路径,取其大者。

只需要计算这两个情况的路径距离,并取其大者,就是该二叉树的最大距离。


下面是实现代码:

struct node {  node *pLeft;  node *pRight;  int nMaxLeft;  int nMaxRight;  };  int nMaxLen = 0;  void FindMaxLen(node* root)  {  if(root==NULL)    return;    if(root->pLeft==NULL)  root->nMaxLeft=0;  if(root->pRight==NULL)  root->pRight=0;   if(root->pLeft!=NULL)  {  FindMaxLen(root->pLeft);  }   if(root->pRight!=NULL)  {  FindMaxLen(root->pRight);  }   if(root->pLeft!=NULL)  //左子树最大距离{  int nTempMax=0;  if(root->pLeft->nMaxLeft>root->pLeft->nMaxRight)  nTempMax=root->pLeft->nMaxLeft;  else  nTempMax=root->pLeft->nMaxRight;  root->nMaxLeft=nTempMax+1;  }   if(root->pRight!=NULL)  //右子树最大距离{  int nTempMax=0;  if(root->pRight->nMaxLeft>root->pRight->nMaxRight)  nTempMax=root->pRight->nMaxLeft;  else  nTempMax=root->pRight->nMaxRight;  root->nMaxRight=nTempMax+1;  }  if(root->nMaxLeft+root->nMaxRight>nMaxLen)  //更新最大距离 nMaxLen=root->nMaxLeft+root->nMaxRight;  }  



1 0
原创粉丝点击