第十一题(求二叉树中节点的最大距离)
来源:互联网 发布:淘宝卖家寄快递的软件 编辑:程序博客网 时间:2024/04/28 12:00
第11 题
求二叉树中节点的最大距离...
如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
求一棵二叉树中相距最远的两个节点之间的距离。
分析:
采用递归求解
对于一个根节点,取 左子树最大深度+右子树最大深度,左子树最大距离,右子树最大距离这三种情况的最大值,最大值就是所要求的节点的最大距离。
结束条件为:对于叶子节点,深度,最大距离都是0。采用引用传递参数的方式,取得子树的深度,子树的最大距离通过返回值传递。
代码:
<pre name="code" class="cpp">namespace MS100P_11{struct TreeNode{TreeNode* left;TreeNode* right;};int max(int a, int b){ return a > b ? a : b; }int helper(TreeNode* root, int& depth)//返回的是最大距离,depth为当前深度{if (root == NULL){depth = 0;return 0;}int leftDepth, rightDepth;int maxDistanceLeft = helper(root->left,leftDepth);int maxDistanceRight = helper(root->right, rightDepth);depth = leftDepth > rightDepth ? leftDepth : rightDepth;//当前最大深度 depth+=1;return max(maxDistanceLeft, max(maxDistanceRight, leftDepth + rightDepth));}int maxDistance(TreeNode* root){int depth;return helper(root, depth);}}
0 0
- 第十一题(求二叉树中节点的最大距离)
- 【100题】第十一题(二叉树中节点的最大距离)
- 求二叉树中节点的最大距离(递归)
- 【二叉树】求二叉树中节点的最大距离
- 求二叉树中节点最大距离
- 求二叉树中结点的最大距离 【微软面试100题 第十一题】
- 微软100题第11题(求二叉树中节点的最大距离)
- 3.8求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 11、求二叉树中节点的最大距离...
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- spring quartz定时器
- Swift学习——Swift基础详解(一)
- 面试题(十二)谈谈递归
- heapq--Python列表的最小堆排序算法
- iOS中属性与成员变量的区别
- 第十一题(求二叉树中节点的最大距离)
- IP地址的分类——a,b,c 类是如何划分的
- 超快速理解const修饰的作用
- 02js基础 js基础语法
- Object.hashCode()方法与System.identityHashCode(object)的区别
- SICP 习题 (1.42)解题总结
- C++杂记:堆栈的用法与区别
- shell脚本知识
- 关于Android Bitmap Blending – Color Channels