首页 > 其他分享 >求二叉树节点的最大距离

求二叉树节点的最大距离

时间:2023-03-04 11:32:47浏览次数:39  
标签:tmp right nmaxleft nmaxright 距离 二叉树 root 节点 left


距离即为节点间的边数。

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);
}


标签:tmp,right,nmaxleft,nmaxright,距离,二叉树,root,节点,left
From: https://blog.51cto.com/u_15990681/6099886

相关文章