zoukankan      html  css  js  c++  java
  • 求二叉树中节点的最大距离

    如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,
    我们姑且定义距离为两节点之间边的个数。
    写一个程序,
    求一棵二叉树中相距最远的两个节点之间的距离。

      二叉树的数据结构:

    1 struct BinaryTreeNode
    2 {
    3     int nData;
    4 
    5     BinaryTreeNode *lChild;
    6     BinaryTreeNode *rChild;
    7 };

      思路:这里的最大距离出现的地方有两种情况,一种是穿过根节点的两个叶节点的最大距离,另一种情况是左子树的最大距离或右子树的最大距离。对于前一种情况我们只需返回左右子树的深度再加上根节点下的两条边即可,因此我们可以定义两个变量nDeepth和nMaxDistance,其中nDeepth用来存储二叉树的深度,nMaxDistance用来存储左右子树最大距离的最大值,因为函数只可以返回一个值,因此我们需要把这两个变量封装在一个结构内返回。

      基于以上分析,可写出以下代码:

    封装nDeepth和nMaxDistance:

    1 struct RESULT
    2 {
    3     int nDeepth;
    4     int nMaxDistance;
    5 };

    获取最大距离的代码:

     1 RESULT GetMaxDistance(BinaryTreeNode *root)
     2 {
     3     if (NULL == root)
     4     {
     5         RESULT Empty;
     6 
     7         // 这里的深度定义为边的数目,不是节点的数目,迎合题目定义的距离的含义
     8         Empty.nDeepth = -1;
     9         Empty.nMaxDistance = 0;
    10 
    11         return (Empty);
    12     }
    13 
    14     // 递归获取左右子树的最大距离
    15     RESULT Left = GetMaxDistance (root->lChild);
    16     RESULT Right = GetMaxDistance (root->rChild);
    17 
    18     RESULT Current;
    19 
    20     Current.nDeepth = Left.nDeepth > Right.nDeepth ? (Left.nDeepth + 1) : (Right.nDeepth + 1);
    21 
    22     int nMaxDistance1 = Left.nMaxDistance > Right.nMaxDistance ? Left.nMaxDistance : Right.nMaxDistance;
    23     int nMaxDistance2 = Left.nDeepth + Right.nDeepth + 2;
    24 
    25     Current.nMaxDistance = nMaxDistance1 > nMaxDistance2 ? nMaxDistance1 : nMaxDistance2;
    26 
    27     return (Current);
    28 }
  • 相关阅读:
    【USACO2017JAN】 Promotion Counting
    【POJ 3468】 A Simple Problem with Integers
    【HDU 1754】 I Hate It
    【Codeforces 20C】 Dijkstra?
    【POJ 2407】 Relatives
    BZOJ5249 九省联考2018IIIDX(线段树+贪心)
    BZOJ5251 八省联考2018劈配(网络流)
    BZOJ4200 NOI2015小园丁与老司机(动态规划+上下界网络流)
    BZOJ3876 AHOI/JSOI2014支线剧情(上下界网络流)
    LOJ117 有源汇有上下界最小流(上下界网络流)
  • 原文地址:https://www.cnblogs.com/ldjhust/p/3052862.html
Copyright © 2011-2022 走看看