Monday, November 1, 2010

Data Structures Part 5

How do you convert a tree into an array? 

          
The conversion is based on these rules


If i > 1, i/2 is the parent
If 2*i > n, then there is no left child, else 2*i is the left child.
If (2*i + 1) > n, then there is no right child, else (2*i + 1) is the 
right child.



Converting a tree to an array is very easy

Suppose we have a tree like this


      A
  B       C
 D E     F G


The array representation would be


a[1] a[2] a[3] a[4] a[5] a[6] a[7]
  A    B    C    D    E    F    G


That is, for every node at position i in the array, its left child 
will be stored at position (2*i) and right child at (2*i + 1).
The root starts at position 1. 

A full N-ary tree has M non-leaf nodes, how many leaf nodes does it have? 
Use Geometric progression.


M + (N ^ (n-1)) = (1 - (N ^ n)) / (1 - N)

Here (N ^ (n-1)) is the number of leaf-nodes.

Solving for this leads to the answer

Leaf nodes = M * (N - 1) + 1



Suppose you have a 3-ary tree


                A
      B         C         D
   E  F  G   H  I  J   K  L  M



So, here M=4 and N=3. So using the formula above, 


Leaf nodes = M * (N - 1) + 1 = 4 * (3 - 1) + 1 = 9 

No comments:

Post a Comment