二叉树中任意两个节点间的最大距离

来源:互联网 发布:linux 挂载有数据硬盘 编辑:程序博客网 时间:2024/06/05 07:36

求一个二叉树中任意两个节点间的最大距离,两个节点的距离的定义是这两个节点间边的个数,优化时间空间复杂度。

两种情况:
情况A: 左子树的最大深度,通过根节点,右子树的最大深度
情况B: 不穿过根节点,而是左子树或右子树的最大距离路径
三者比较,取最大的

[cpp] view plaincopy
  1. void FindMaxDis(BSTreeNode *pNode, int &deepth, int &maxdis)  
  2. {  
  3.     if (pNode==NULL)  
  4.     {  
  5.         deepth=0;maxdis=0;  
  6.         return;  
  7.     }  
  8.     int l_deepth=0,r_deepth=0;  
  9.     int l_maxdis=0,r_maxdis=0;  
  10.   
  11.     if (pNode->m_pleft)  
  12.         FindMaxDis(pNode->m_pleft,l_deepth,l_maxdis);  
  13.     if (pNode->m_pright)  
  14.         FindMaxDis(pNode->m_pright,r_deepth,r_maxdis);  
  15.   
  16.     deepth = (l_deepth > r_deepth ? l_deepth : r_deepth) + 1;  
  17.     maxdis = l_maxdis > r_maxdis ? l_maxdis : r_maxdis ;  
  18.     maxdis = (l_deepth+r_deepth) > maxdis ? (l_deepth+r_deepth) : maxdis;  
  19. }  
  20. int FindMaxDis(BSTreeNode *pNode)  
  21. {  
  22.     int deepth, maxdis;  
  23.     FindMaxDis(pNode,deepth,maxdis);  
  24.     return maxdis;  
  25. }  

原文来自:http://blog.csdn.net/seasky11/article/details/12129165
0 0
原创粉丝点击