CSCSCS
CSCSCS

Reputation: 79

Array representation of Binary Tree (print method)

I am done with my assignment and just want the output to look nice, so I need a print method which can print a tree structure of a binary tree (represented by an array).

In an array representation of a tree:

if node: i

Child: 2*i, 2*i+1

Parent: i/2

For example, for array

value 10 5 8 2 3 6 7
index 1  2 3 4 5 6 7

Tree representation should be:

     10
  5      8
2   3  6   7

It does not have to be EXACT same representation as shown above. It can be any representation that shows the tree properly.

Can someone help me with it? Thank you

Upvotes: 2

Views: 8944

Answers (2)

murage kibicho
murage kibicho

Reputation: 644

This is the code for anyone looking. (*I haven't written in Java for a long time)

public class PrintTree{
 
    
    static int PowerOf2(int power)
    {
        return (1<<power);
    }
    
    static void PrintTreeArray(int array[], int arrayLength)
    {
    int currentLevel = 0;
    int maxPerLevel = PowerOf2(currentLevel);
    for(int i = 0; i < arrayLength; i++)
    {
        if(i == maxPerLevel-1)
        {
            System.out.println("\n");
            currentLevel++;
            maxPerLevel = PowerOf2(currentLevel);
        }
        System.out.print(" "+array[i]);
    }
    }

     public static void main(String []args)
     {
        int[] array = new int[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14};
        PrintTreeArray(array,15);
     }
}

Upvotes: 0

xpda
xpda

Reputation: 15813

It should be pretty easy. For the first row, print 1. Second row, print array elements 2, 3. Third row, print array elements 4,5,6,7. Fourth row, 8,9,10,11,12,13,14,15. See the pattern? Each row, you print elements 2^n to 2^(n+1) - 1, where the top row is zero.

This assumes if there are some nodes without two children, those null children still use space in the array.

Upvotes: 2

Related Questions