在二叉树中,找到距离最远的两个节点的距离

本文探讨了在二叉树中寻找两个节点间最大距离的问题,并提供了两种不同的递归算法实现方案。通过分析树结构,文章详细解释了如何计算从根节点到最远节点的距离,为读者提供了一个清晰的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在二叉树中,找到距离最远的两个节点的距离


在二叉树中,找到距离最远的两个节点的距离。在上面的二叉树中,最远的节点的距离是:4(路径是2-3-13-5-2)。

解决思路:递归。最远的两个节点,1) 要么都在根节点的左子树,2) 要么在都在根节点的右子树,3) 要么分别在左子树和右子树,4) 还有可能是深度最深的节点和根节点距离最远。


我的代码如下(虽然未测试,但是逻辑正确):
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int longest_dis(Node* root)  
  2. {  
  3.     int height1, height2;  
  4.   
  5.     if( root==NULL)  
  6.         return 0;  
  7.   
  8.     if( root->left == NULL ) && ( root->right == NULL )  
  9.         return 0;  
  10.   
  11.     height1 = height(root->left); // height(Node* node) returns the height of a tree rooted at node  
  12.     height2 = height(root->right);  
  13.   
  14.     if( root->left != NULL ) && ( root->right == NULL )  
  15.         return max(height1+1, longest_dis(root->left) );  
  16.   
  17.     if( root->left == NULL ) && ( root->right != NULL )  
  18.         return max(height2+1, longest_dis(root->right) );  
  19.   
  20.     return max(height1+height2+2, longest_dis(root->left), longestdis(root->right) );  
  21. }  

网上别人的代码如下:
  1: int maxDistance(Node * root)  
  2: { 
  3:   int depth; 
  4:   return helper(root, depth); 
  5: } 
  6: int helper(Node * root, int &depth)  
  7: { 
  8:   if (root == NULL)  
  9:   { 
 10:     depth = 0;  
 11:     return 0; 
 12:   } 
 13:   int ld, rd; 
 14:   int maxleft = helper(root->left, ld); 
 15:   int maxright = helper(root->right, rd); 
 16:   depth = max(ld, rd)+1; 
 17:   return max(maxleft, max(maxright, ld+rd)); 
 18: }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值