在二叉树中,找到距离最远的两个节点的距离
2014-10-17 15:22
295 查看
在二叉树中,找到距离最远的两个节点的距离
在二叉树中,找到距离最远的两个节点的距离。在上面的二叉树中,最远的节点的距离是:4(路径是2-3-13-5-2)。
解决思路:递归。最远的两个节点,1) 要么都在根节点的左子树,2) 要么在都在根节点的右子树,3) 要么分别在左子树和右子树,4) 还有可能是深度最深的节点和根节点距离最远。
我的代码如下(虽然未测试,但是逻辑正确):
[cpp] view
plaincopy
int longest_dis(Node* root)
{
int height1, height2;
if( root==NULL)
return 0;
if( root->left == NULL ) && ( root->right == NULL )
return 0;
height1 = height(root->left); // height(Node* node) returns the height of a tree rooted at node
height2 = height(root->right);
if( root->left != NULL ) && ( root->right == NULL )
return max(height1+1, longest_dis(root->left) );
if( root->left == NULL ) && ( root->right != NULL )
return max(height2+1, longest_dis(root->right) );
return max(height1+height2+2, longest_dis(root->left), longestdis(root->right) );
}
网上别人的代码如下:
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: }
相关文章推荐
- 求二叉树中距离最远的两个叶子节点间的距离?
- 二叉树的两个节点之间最远的距离
- 在二叉树中,距离最远的两个节点的距离
- 求一个二叉树中距离最远的两个节点
- 二叉树中相距最远的两个节点之间的距离
- 求二叉树中两个节点的最远距离
- 求二叉树中节点的最大距离 即二叉树中相距最远的两个节点之间的距离
- 查找二叉树最远两个节点的距离
- 二叉树中相距最远的两个节点之间的距离
- 求二叉树中两个节点最远的距离
- 二叉树系列——二叉树的最大距离(即相距最远的两个叶子节点,编程之美,百度面试题)
- 求二叉树中距离最远的两个叶子节点的距离
- Java实现:在二叉树中,求距离最远的两个节点的距离
- 二叉树中相距最远的两个节点之间的距离
- 【每日面试题】求一个二叉树中任意两个节点间的最大距离
- 微软等数据结构+算法面试100题(38)-- 二叉树中任意两个节点间的最大距离
- 求二叉树两节点的最远距离
- 求一个二叉树中任意两个节点间的最大距离
- 算法:求二叉树中两个节点的最大距离
- (算法)二叉树两个结点的最远距离