二叉树中节点的最大距离
来源:互联网 发布:淘宝有好货怎么参加 编辑:程序博客网 时间:2024/05/01 16:34
问题定义
如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,我们姑且定义"距离"为两节点之间边的个数。写一个程序求一棵二叉树中相距最远的两个节点之间的距离。
《编程之美》的解法
书中对这个问题的分析是很清楚的,我尝试用自己的方式简短覆述。
计算一个二叉树的最大距离有两个情况:
- 情况A: 路径经过左子树的最深节点,通过根节点,再到右子树的最深节点。
- 情况B: 路径不穿过根节点,而是左子树或右子树的最大距离路径,取其大者。
只需要计算这两个情况的路径距离,并取其大者,就是该二叉树的最大距离。
// 数据结构定义struct NODE{ NODE* pLeft; // 左子树 NODE* pRight; // 右子树 int nMaxLeft; // 左子树中的最长距离 int nMaxRight; // 右子树中的最长距离 char chValue; // 该节点的值};int nMaxLen = 0;// 寻找树中最长的两段距离void FindMaxLen(NODE* pRoot){ // 遍历到叶子节点,返回 if(pRoot == NULL) { return; } // 如果左子树为空,那么该节点的左边最长距离为0 if(pRoot -> pLeft == NULL) { pRoot -> nMaxLeft = 0; } // 如果右子树为空,那么该节点的右边最长距离为0 if(pRoot -> pRight == NULL) { pRoot -> nMaxRight = 0; } // 如果左子树不为空,递归寻找左子树最长距离 if(pRoot -> pLeft != NULL) { FindMaxLen(pRoot -> pLeft); } // 如果右子树不为空,递归寻找右子树最长距离 if(pRoot -> pRight != NULL) { FindMaxLen(pRoot -> pRight); } // 计算左子树最长节点距离 if(pRoot -> pLeft != NULL) { int nTempMax = 0; if(pRoot -> pLeft -> nMaxLeft > pRoot -> pLeft -> nMaxRight) { nTempMax = pRoot -> pLeft -> nMaxLeft; } else { nTempMax = pRoot -> pLeft -> nMaxRight; } pRoot -> nMaxLeft = nTempMax + 1; } // 计算右子树最长节点距离 if(pRoot -> pRight != NULL) { int nTempMax = 0; if(pRoot -> pRight -> nMaxLeft > pRoot -> pRight -> nMaxRight) { nTempMax = pRoot -> pRight -> nMaxLeft; } else { nTempMax = pRoot -> pRight -> nMaxRight; } pRoot -> nMaxRight = nTempMax + 1; } // 更新最长距离 if(pRoot -> nMaxLeft + pRoot -> nMaxRight > nMaxLen) { nMaxLen = pRoot -> nMaxLeft + pRoot -> nMaxRight; }}
这段代码有几个缺点:
1、算法在二叉树结构体中加入了侵入式(intrusive)的变量nMaxLeft, nMaxRight
2、使用了全局变量 nMaxLen。每次使用要额外初始化
3、逻辑比较复杂,也有许多 NULL 相关的条件测试
我的解法:根据最大距离的定义,递归求解
//return MaxDistance of tint MaxDistance(Tree * t){ if (t == 0) return 0; int lheight = height(t->left)-1;//-1:边的数目=节点数目-1 int rheight = height(t->right)-1; int lDis = MaxDistance(t->left); int rDis = MaxDistance(t->right); return max(lheight + rheight + 2,max(lDis,rDis));//+2:根节点到左右孩子的边} //returns height of tree with root tint height(Tree * t){ if (t == 0) return 0; return 1 + max(height(t->left),height(t->right));}
1、http://blog.163.com/shi_shun/blog/static/2370784920109264337177/
2、http://www.cs.duke.edu/courses/spring00/cps100/assign/trees/diameter.html
3、http://blog.csdn.net/jiyanfeng1/article/details/7950587
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 【二叉树】求二叉树中节点的最大距离
- 二叉树中节点的最大的距离
- 求二叉树中节点最大距离
- 3.8求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- SQL Server大负载的生产环境下的性能优化:初识元数据优化
- 超极本™ 触摸屏 - 一种全新的动手方式
- arduino之红外
- java.util.concurrent介绍
- JQuery获取当前屏幕的高度宽度的实现代码
- 二叉树中节点的最大距离
- [Urgent]Technical Support Engineer II - 2013/10/18
- 输入星期值,输出英文【多分支】
- getOutputStream() has already been called for this response
- Android杂谈——分隔线
- EDM许可式邮件营销图片使用分析
- mxgraph生成orgchart图
- 判断IE的各个不同版本
- user web