Order of elements in perfectly balanced tree

240 Views Asked by At

I have a hard time visualizing how will my program insert the elements. Here's the code that the teacher gave us:

int arr[] = { 3, -2, 11, 7, 12, 1, 4, 5, 33, 13 };
int n = 10;
int cnt = 0;

typedef struct node*po;

struct node {
    int data;
    po left;
    po right;
};

po ibd(int n) {
    po holder;
    if (n>0) {
        int nl = n / 2;
        int nr = n - nl - 1;
        holder = new node;
        holder->data = arr[cnt++];
        holder->left = ibd(nl);
        holder->right = ibd(nr);
        return holder;
    }
    else {
        return NULL;
    }
}

I sadly can't understand and visualize how it puts the elements in the tree. From what I can understand it uses recursively divide and conquer algorithm to split the array into two parts and add the elements, however I can't understand which element becomes the root. Can somebody help me visualize how the tree would look after everything has been inserted?

1

There are 1 best solutions below

4
On

When working with trees, I like to draw a node something like this:

+--------------+---------------+  
|            Data              |  
+--------------+---------------+  
|  Pointer to  |   Pointer to  |  
| left subtree | right subtree |  
+--------------+---------------+  

When I make one node point to another, I use arrows from the appropriate left or right pointer to the new node. This helps me visualize the tree.

There are many resources that show how to draw trees.

Once the tree is drawn, follow the arrows when adding a new node.