Could you please help how to prove by induction that current algorithm which tests if the binary search tree is of AVL type is correct?
int checkHeight(TreeNode root){
if(root == null)
return 0;
int leftHeight := checkHeight(root.left);
if(leftHeight == -1)
return -1;
int rightHeight := checkHeight(root.right);
if(rightHeight == -1)
return -1;
int heightDiff := Math.abs(leftHeight - rightHeight);
if(heightDiff > 1)
return -1;
else
return max(leftHeight, rightHeight) + 1;
}
I tried such proof.
Basis: root is null - return 0.
Induction step: if we have a tree, where B is a root then in the leaf levels the height is 0, moving to the top we take max(0, 0) = 0 and add 1. The height is correct. Calculating the difference between the height of left node and the height of the right one 0-0 = 0 we obtain that it is not bigger than 1. The result is 0+1 =1 - the correct height. For all binary search trees, such algorithm is correct.