「Cracking the Coding Interview」から次の問題を解決しています: 二分木のバランスが取れているかどうかをチェックする関数を実装します。バランスの取れたツリーとは、ノードの 2 つのサブツリーの高さの差が 1 を超えないようなツリーです。
本のサンプル ソリューション (以下にコピー) では、(a) ノードの左と右のサブツリーのバランスが取れている場合、ノードから発するツリーのバランスが取れていると想定しています。(b) ノード自体のバランスがとれている。なぜこれが事実なのか理解しようとしていますか?上記の 2 つの条件が満たされていることは、ノードから発するツリー全体のバランスが取れていることをどのように証明しますか?
ありがとう
public static boolean isBalanced(TreeNode root)
{
if (checkHeight(root)==-1)
return false;
return true;
}
public static int checkHeight(TreeNode root)
{
//base case
if (root == null)
return 0;
//is left subtree balanced
int leftHeight = checkHeight(root.leftChild);
if (leftHeight == -1)
return -1;
//is right subtree balanced
int rightHeight = checkHeight(root.rightChild);
if (rightHeight == -1)
return -1;
//is current node balanced
int heightDiff = leftHeight - rightHeight;
if (Math.abs(heightDiff) > 1)
return -1;
return (Math.max(leftHeight, rightHeight) + 1);
}