求二叉树中节点的最大距离
来源:互联网 发布:穿过的内衣裤出售 淘宝 编辑:程序博客网 时间:2024/06/06 23:52
上一篇的《求二叉树中节点的最大距离 》显得有点走火入魔了,参考过别人的算法解释,事实上不需要考虑得那么复杂。使用以下C代码就可以解决了。
解释一下,get_depth函数是求二叉树的深度,用的是递归算法:一棵二叉树的深度就是它的左子树的深度和右子树的深度,两者的最大值加一。
get_max_distance函数是求二叉树的最大距离,也是用递归算法:首先算出经过根节点的最大路径的距离,其实就是左右子树的深度和;然后分别算出左子树和右子树的最大距离,三者比较,最大值就是当前二叉树的最大距离了。
这个算法不是效率最高的,因为在计算二叉树的深度的时候存在重复计算。但应该是可读性比较好的,同时也没有改变原有二叉树的结构和使用额外的全局变量。
- /*
- * 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函数是求二叉树的最大距离,也是用递归算法:首先算出经过根节点的最大路径的距离,其实就是左右子树的深度和;然后分别算出左子树和右子树的最大距离,三者比较,最大值就是当前二叉树的最大距离了。
这个算法不是效率最高的,因为在计算二叉树的深度的时候存在重复计算。但应该是可读性比较好的,同时也没有改变原有二叉树的结构和使用额外的全局变量。
0 0
- 【二叉树】求二叉树中节点的最大距离
- 求二叉树中节点最大距离
- 3.8求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 11、求二叉树中节点的最大距离...
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中两个节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- php学习之道:call_user_func和call_user_func_array的用法
- java实例2
- Java集合框架总结(4)——List接口的使用
- 雾山的Android学习笔记---消息机制(三) .
- cocos项目导入其他源文件时添加依赖库时,头文件提示找不到目录中的文件
- 求二叉树中节点的最大距离
- Ubuntu下crontab命令的用法
- Java集合框架总结(5)——Map接口的使用
- mailcore(一)
- java解析oracle日志,获取指定日期后的更新和插入数据
- 题目1504:把数组排成最小的数
- ACM从零开始---电子科大POJ "直接插入排序"
- ubuntu下安装go语言;sublime+gocode搭建;go的卸载和环境变量配个人.bashrc;2空位3个网
- OTN 交换& P-OTN有效降低100G 网络成本 (三)