GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Count total number of column in a binary tree ?

asked Mar 17, 2016 by no3

1 Answer

You can keep an extra information 'col' at each node then you can find number of columns recursively as below :

int min, max;

//  updating col while inserting
void insert(node * newnode , node * t)
{
    if (newnode->key > t->key)
    {
        if (t->right == NULL)
        {
            t->right = newnode;
            newnode->col = t->col + 1;
        }
        else
        {
            insert (newnode,t->right);
        }        
    }
    else
    {
        if (t->left == NULL)
        {
            t->left = newnode;
            newnode->col = t->col - 1;
        }
        else
        {
            insert (newnode,t->left);
        }
    }
}

void columns(node* t)
{
    if (t == NULL)
        return;

    if (t->col < min)
        min = t->col;

    if (t->col > max)
        max = t->col;

    columns(t->left);
    columns(t->right);
}

void getColumn(node* root)
{
    columns(root);
    return max - min + 1;
}

 

answered Mar 17, 2016 by utkarsh111
...