struct Node{
Node * left;
Node * right;
int lmaxlen;
int rmaxlen;
char val;
};
int maxlen = 0;
//查找二叉树中最远的两个节点
void search(Node * root){
if(root == NULL){
return ;
}
if(root->left != NULL){
search(root->left);
}else{
root->lmaxlen = 0;
}
if(root->right != NULL){
search(root->right);
}else{
root->rmaxnlen = 0;
}
if(root->left != NULL){
int tpmaxlen = 0;
if(root->left->lmaxlen > root->left->rmaxlen){
tpmaxlen = root->left->lmaxlen;
}else{
tpmaxlen = root->left->raxlen;
}
root->lmaxlen = tpmaxlen + 1;
}
if(root->right != NULL{
int tpmaxlen = 0;
if(root->right->rmaxlen > root->right->lmaxlen){
tpmaxlen = root->right->rmaxlen;
}else{
tpmaxlen = root->right->lmaxlen;
}
root->lmaxlen = tpmaxlen + 1;
}
if(root->lmaxlen + root->rmaxlen > maxlen){
maxlen = root->lmaxlen + root->rmaxlen;
}
}查找二叉树最远两个节点的距离
最新推荐文章于 2021-09-06 19:51:33 发布
本文介绍了一种算法用于在二叉树中找到距离最远的两个节点,并更新最大距离。通过递归遍历树的左右子节点,计算每个节点到最近祖先节点的距离,最终找出最大距离。
698

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



