上一篇的《求二叉树中节点的最大距离 》显得有点走火入魔了,参考过别人的算法解释,事实上不需要考虑得那么复杂。使用以下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函数是求二叉树的最大距离,也是用递归算法:首先算出经过根节点的最大路径的距离,其实就是左右子树的深度和;然后分别算出左子树和右子树的最大距离,三者比较,最大值就是当前二叉树的最大距离了。
这个算法不是效率最高的,因为在计算二叉树的深度的时候存在重复计算。但应该是可读性比较好的,同时也没有改变原有二叉树的结构和使用额外的全局变量。
求二叉树中节点的最大距离(递归算法)
最新推荐文章于 2021-06-01 17:17:43 发布