原文地址: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