求二叉树中节点的最大距离(递归算法)

本文介绍了一种求解二叉树中节点间最大距离的简单算法,通过递归方式计算左右子树的深度,并比较得出最大距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇的《求二叉树中节点的最大距离 》显得有点走火入魔了,参考过别人的算法解释,事实上不需要考虑得那么复杂。使用以下C代码就可以解决了。

/* * return the depth of the tree */ int get_depth(Tree *tree) { int depth = 0; if ( tree ) { int a = get_depth(tree->left); int b = get_depth(tree->right); depth = ( a > b ) ? a : b; depth++; } return depth; } /* * return the max distance of the tree */ int get_max_distance(Tree *tree) { int distance = 0; if ( tree ) { // get the max distance connected to the current node distance = get_depth(tree->left) + get_depth(tree->right); // compare the value with it's sub trees int l_distance = get_max_distance(tree->left); int r_distance = get_max_distance(tree->right); distance = ( l_distance > distance ) ? l_distance : distance; distance = ( r_distance > distance ) ? r_distance : distance; } return distance; }

解释一下,get_depth函数是求二叉树的深度,用的是递归算法:一棵二叉树的深度就是它的左子树的深度和右子树的深度,两者的最大值加一。

get_max_distance函数是求二叉树的最大距离,也是用递归算法:首先算出经过根节点的最大路径的距离,其实就是左右子树的深度和;然后分别算出左子树和右子树的最大距离,三者比较,最大值就是当前二叉树的最大距离了。

这个算法不是效率最高的,因为在计算二叉树的深度的时候存在重复计算。但应该是可读性比较好的,同时也没有改变原有二叉树的结构和使用额外的全局变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值