5

In the book Introduction To Algorithms - A Creative Approach, Question 4.18:

The AVL algorithms that were presented in Section 4.3.4 require balanced factors with three possible values: 1, 0, or -1. To represent three values we need 2 bits. Suggest a method for implementing these algorithms (with only a slight modification) with only 1 extra bit per node.

I have implemented AVL tree by recording each node's height instead of a balanced factor.

But I have no idea how to represent three values (1, 0, -1) with only 1 bit. I guess there must be some other information that can be employed to represent 1,0,-1, together with the 1 bit.

Could anyone help on this question?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Guocheng
  • 543
  • 3
  • 15

2 Answers2

1

If node don't have got two sons -you can calculate it else you can remember it in sons: one bit in left son and one in right son.

Newbie
  • 435
  • 2
  • 6
  • 13
-1

Subtract the heights, int balance = left->height - right->height, and then use balance <= -1, balance == 0 and balance >= 1. No need for additional bits, besides the height.

Keep in each node a single bit with the meaning "this subtree is of a lower height than its sibling". There is a 1:1 correspondence between the balance factor at a node and the extra bits in its children.

left: 0, right: 0 <-> balance: 0
left: 0, right: 1 <-> balance: 1
left: 1, right: 0 <-> balance: -1
left: 1, right: 1 <-> invalid
chill
  • 16,470
  • 2
  • 40
  • 44
  • 1
    I have implemented AVL tree by recording each node's height instead of a balanced factor. But "height" occupies at least 8 bits. – Guocheng Nov 24 '13 at 09:50
  • That took _some_ time to correct. The balance influences a nodes _behaviour_ when heights change: with instance morphing, this can be kept by in each node's class. – greybeard Jan 20 '17 at 11:06