数据结构——二叉树的直径

原文地址:Diameter of a Binary Tree

树的直径(有时也称作宽度),指的是树中的两个叶子节点之间最长路径的节点的数目,下面的图显示了两个树的直径都是9,形成最长路径的两个端点的叶子节点被加上了阴影(注意每个树中长度为9的路径不止一个,但是没有比9再更长的路径了)。

![这里写图片描述](https://img-blog.csdn.net/20161126152341449) 一个树T的直径是下面几条里面最长的: - T的左子树的直径 - T的右子树的直径 - 两个叶子之间穿过T的根的最长路径(这个可以通过计算这个树的子树的高度获得) 实现:
// Recursive optimized Java program to find the diameter of a
// Binary Tree

/* Class containing left and right child of current
 node and key value*/
class Node
{
    int data;
    Node left, right;

    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}

/* Class to print the Diameter */
class BinaryTree
{
    Node root;

    /* Method to calculate the diameter and return it to main */
    int diameter(Node root)
    {
        /* base case if tree is empty */
        if (root == null)
            return 0;

        /* get the height of left and right sub trees */
        int lheight = height(root.left);
        int rheight = height(root.right);

        /* get the diameter of left and right subtrees */
        int ldiamet
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值