<span style="font-size:18px;"> public static int height(TreeNode t)
// postcondition: returns height of tree with root t
{
if (t == null)
{
return 0;
}
else
{
return 1+Math.max(height(t.left),height(t.right));
}
}
public static int getMaxdis(TreeNode tree){
// post: return Max distance of tree
if (tree == null) return 0;
int lheight = height(tree.left);
int rheight = height(tree.right);
int ldiameter = getMaxdis(tree.left);
int rdiameter = getMaxdis(tree.right);
return Math.max(lheight + rheight,Math.max(ldiameter,rdiameter));
}</span>求二叉树中节点的最大距离 即二叉树中相距最远的两个节点之间的距离
最新推荐文章于 2023-05-01 14:01:00 发布
本文介绍了一种计算二叉树高度及最大直径的方法。通过递归函数实现,首先定义了计算树高度的方法,然后利用该方法计算左子树和右子树的最大高度,并基于此计算树的最大直径。
1274

被折叠的 条评论
为什么被折叠?



