私はgetDiameter()関数を作成したバイナリツリーの直径を計算します。この関数では、バイナリツリーの高さを返すBinary TreeのfindHeight()関数を呼び出す必要があります。 code1とcode2の高さを計算する2つの関数は、概念の点で少し異なります。 私は単一ノード(ルートのみ)のツリーの高さが1であり、コード2では単一ノードのツリーの高さが0であると考えています。コード1の基本ケースでは、0を返していますcode2私は-1を返しました。 Iは、コード1、コード2の概念の両方が高さを見つけることが正しい木の高さを再帰的に使用して二分木の直径を計算しますか?
public static int getDiameter(BinaryTreeNode root) {
if (root == null)
return 0;
int rootDiameter = findHeight(root.getLeft()) + findHeight(root.getRight()) + 1;
int leftDiameter = getDiameter(root.getLeft());
int rightDiameter = getDiameter(root.getRight());
return Math.max(rootDiameter, Math.max(leftDiameter, rightDiameter));
}
code1
public static int findHeight(BinaryTreeNode node) {
if(node == null)
return 0;
else {
return 1+Math.max(findHeight(node.left), findHeight(node.right));
}
}
Code 2
public static int findHeight(BinaryTreeNode node) {
if(node == null)
return -1;
else {
return 1+Math.max(findHeight(node.left), findHeight(node.right));
}
}