您的位置:首页 > 其它

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

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: }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: