在二叉树中,找到距离最远的两个节点的距离
在二叉树中,找到距离最远的两个节点的距离。在上面的二叉树中,最远的节点的距离是:4(路径是2-3-13-5-2)。
解决思路:递归。最远的两个节点,1) 要么都在根节点的左子树,2) 要么在都在根节点的右子树,3) 要么分别在左子树和右子树,4) 还有可能是深度最深的节点和根节点距离最远。
我的代码如下(虽然未测试,但是逻辑正确):
- 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: }
本文探讨了在二叉树中寻找两个节点间最大距离的问题,并提供了两种不同的递归算法实现方案。通过分析树结构,文章详细解释了如何计算从根节点到最远节点的距离,为读者提供了一个清晰的解决方案。

5431

被折叠的 条评论
为什么被折叠?



