Sunday, August 29, 2010

Printing a tree on a console


You are given a tree, and you need to print it on a console. The root node should be at the center of the first row. Left child of the root should be at the center of the first half of the console, and right child of the root should be at the center of the second half of the console. Similarly, the left child of the left child of the root should be at the center of the first quarter of the console, and so on. You have a function printxy(row, column, data) which prints at the give row and column.

Answer:



void print(int row, int startCol, int endCol, Node tree)
{
if(tree==NULL)
return;
printxy(row, (startCol+endCol)/2, tree->data);
print(row+1, startCol, (startCol+endCol)/2, tree->left);
print(row+1, (startCol+endCol)/2+1, endCol, tree->right);
}


call print(1, 1, colsInConsole, root);

No comments:

Post a Comment