求二叉树中节点的最大距离

来源:互联网 发布:穿过的内衣裤出售 淘宝 编辑:程序博客网 时间:2024/06/06 23:52
上一篇的《求二叉树中节点的最大距离 》显得有点走火入魔了,参考过别人的算法解释,事实上不需要考虑得那么复杂。使用以下C代码就可以解决了。

[cpp] view plaincopy
  1. /* 
  2.  * return the depth of the tree 
  3.  */  
  4. int get_depth(Tree *tree) {  
  5.     int depth = 0;  
  6.     if ( tree ) {  
  7.         int a = get_depth(tree->left);  
  8.         int b = get_depth(tree->right);  
  9.         depth = ( a > b ) ? a : b;  
  10.         depth++;  
  11.     }  
  12.     return depth;  
  13. }  
  14. /* 
  15.  * return the max distance of the tree 
  16.  */  
  17. int get_max_distance(Tree *tree) {  
  18.     int distance = 0;  
  19.     if ( tree ) {  
  20.         // get the max distance connected to the current node  
  21.         distance = get_depth(tree->left) + get_depth(tree->right);  
  22.         // compare the value with it's sub trees  
  23.         int l_distance = get_max_distance(tree->left);  
  24.         int r_distance = get_max_distance(tree->right);  
  25.         distance = ( l_distance > distance ) ? l_distance : distance;  
  26.         distance = ( r_distance > distance ) ? r_distance : distance;  
  27.     }  
  28.     return distance;  
  29. }  


解释一下,get_depth函数是求二叉树的深度,用的是递归算法:一棵二叉树的深度就是它的左子树的深度和右子树的深度,两者的最大值加一。

get_max_distance函数是求二叉树的最大距离,也是用递归算法:首先算出经过根节点的最大路径的距离,其实就是左右子树的深度和;然后分别算出左子树和右子树的最大距离,三者比较,最大值就是当前二叉树的最大距离了。

这个算法不是效率最高的,因为在计算二叉树的深度的时候存在重复计算。但应该是可读性比较好的,同时也没有改变原有二叉树的结构和使用额外的全局变量。
0 0
原创粉丝点击