1
votes

diagram related to the question

In the attached picture there are two Binary search trees. When I saw this question I thought that first tree is not balanced so it's not an avl tree and as second one is balanced it's obviously an avl tree.

But here the problem is when I saw the answer for this question it was given both (i) & (ii) are avl trees. How come (i) is an avl tree when it's clearly not balanced?

2

2 Answers

0
votes

You are correct that tree 2 is not an AVL tree. The right subtree of the root - the one rooted at 13 - is not balanced. Specifically, its left subtree (the one rooted at 11) has height 1, and its (missing) right subtree has height -1 for a height imbalance of 2.

What’s your source on this problem? Perhaps it’s a typo, or perhaps the tree wasn’t the one that was intended?

0
votes

Short Answer

Yes, both trees can be considered AVL trees if a height of an empty tree is defined as 0.

Long Answer

Let's take a definition of an AVL tree from here:

A balanced binary search tree where the height of the two subtrees (children) of a node differs by at most one

Now, what is the height of a tree? It's a number of edges on the longest path from the root to a leaf.

Let's take a node in question 13 from your example i. Its right subtree is empty and its left subtree consists of a line of 2 nodes - 10 and 11:

               ...
                13
               /
             11 (height = 1)
            /
           10 (height = 0) 
              ...

So, the height of the left subtree is 1 (the longest path from its root 11 to 10 is obviously 1) and that of the right subtree can be considered 0 (please see more here). Hence, the absolute difference of heights is 1.

I believe it's obvious to you that for any other node in the tree i, the absolute difference of subtree heights is not larger than 1, and so the tree is an AVL tree.

Remark

As pointed out by @templatetypedef, however, if a height of an empty subtree is defined as -1, then the tree is no longer an AVL tree because a balance factor at 13 is 1 - (-1) = 2. So, it all depends on how the height of an empty tree is defined. To make matters worse, the height of an empty tree is not defined - please check here.