求二叉树中节点的最大距离

问题定义

 


 

参考资料

[1] http://www.cs.duke.edu/courses/spring00/cps100/assign/trees/diameter.html

 

下面计算的为二叉树中节点的最大距离定义为两节点间的顶点个数。

 

Tree Diameter

 

The function below returns the diameter of a tree. A tree's diameter is defined after the function. Write a recurrence for this function and solve it yielding the running time using big-Oh in terms of the number of nodes in a tree.

 

 

int diameter(Tree * t)

// post: return diameter of t

{

    if (t == 0) return 0;

 

    int lheight = height(tree->left);

    int rheight = height(tree->right);

 

    int ldiameter = diameter(tree->left);

    int rdiameter = diameter(tree->right);

 

    return max(lheight + rheight + 1,

      max(ldiameter,rdiameter));

}

 

The following function returns the height of a tree (the number of nodes on the longest root-to-leaf path).

 

    int height(Tree * t)

    // postcondition: returns height of tree with root t

    {

        if (t == 0)

        {

            return 0;

        }

        else

        {

            return 1 + max(height(t->left),height(t->right));

        }

    }

where the function max returns the largest of its two integer parameters. The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes).

 

 

The diameter of a tree T is the largest of the following quantities:

 

the diameter of T's left subtree

the diameter of T's right subtree

the longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T)

 

[2]

 

进行两次BFS:先从树根A出发进行广度优先搜索(BFS),找到最远的结点B,然后再从结点B出BFS,找到离B最远的结点C,BC就是最大距离。

下面是正确性证明
假设存在结点X和Y,它们的距离是所有结点中最大的;分两种情况讨论:
1. 若路径XY与路径AB有交点O,
...A
...|
X-O--Y
...|
...B
由于|OB| >= |OX|且|OB| >= |OY|,所以,|BX| >= |XY|,|BY| >= |XY|。即从B出发可以构造出最长路径。

2.若路径XY与路径AB无交点,
A...B X...Y
A是树根,XY与B分属不同的子树,假设XY的最近祖先为O,由于
|AB| >= |AO| + |AX|,所以|BY| = |AB| + |AO| + |OY| > |XY|。即从B出发构造出长于XY的路径,与假设XY是最长路径矛盾。

 

[3] http://www.cnblogs.com/miloyip/archive/2010/02/25/binary_tree_distance.html

 

 

 

 

[4] 《编程之美》上的不太清晰的解决办法

 

这种办法其实说它不太清晰是因为:全局变来nMaxLen维护着节点间的最长距离,而递归过程显式的计算了树的最大高度,隐式的计算节点间的最长距离。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值