距离即为节点间的边数。
code:
struct Node
{
Node* left;
Node* right;
int nmaxleft;
int nmaxright;
int vhvalue;
};
int ans;//答案
int findmaxval(Node* root)
{
if (root == NULL) return;
if (root->left == NULL) return root->nmaxleft = 0;
if (root->right == NULL) return root->nmaxright = 0;
if (root->left != NULL) findmaxval(root->left);
if (root->right != NULL) findmaxval(root->right);
if (root->left != NULL)
{
int tmp = 0;
if (root->left->nmaxleft > root->left->nmaxright)
tmp = root->left->nmaxleft;
else
tmp = root->left->nmaxright;
root->nmaxleft = tmp + 1;
}
if (root->right != NULL)
{
int tmp = 0;
if (root->right->nmaxleft > root->right->nmaxright)
tmp = root->right->nmaxleft;
else
tmp = root->right->nmaxright;
root->nmaxright = tmp + 1;
}
ans = max(ans, root->nmaxleft + root->nmaxright);
}