The goal of this assignment is to reinforce the tree data st

The goal of this assignment is to reinforce the tree data structure in C++. Specifically, the assignment is to do the following: Construct a function that will display a binary tree by levels (each level on a separate line). If there is no node at a position in a level, then the function should display NULL. Only levels that contain at least 1 datum should be displayed.

Solution

In this program, I have created two functions and define the structure of Tree. You have to call the function name treelevels with the address of root argument.

struct node                             \\\\ structure of a tree node.
{
    int data;
    struct node* left, *right;
};
void printlevels(struct node* root, int level)          \\\\For printing data of each line.
{
    if (root == NULL)                               \\\\ If the node is not existing then we are printing NULL and we can say it is last node.
    {
        if(level == 1)                                  \\\\ Because we dont want to print the left and right node of NULL node.
        {     
                cout<<\"NULL\"<<\"\\t\";                     \\\\ for printing NULL where no data exist.
        }
        return;
    }
    if (level == 1)                               \\\\    1 means the node reach to particular level now we can print the value.
        cout<<root->data<<\"\\t\";
    else if (level > 1)                         \\\\ We will call the function again and again till it reach to the required level.
    {
        printlevels(root->left, level-1);               \\\\left side
        printlevels(root->right, level-1);              \\\ ight side
    }
}
void treelevels(struct node* root)      \\\\ root is a topmost (root) node of the tree!
{
    int h = tree_height(root);          \\\\ for calculating height of tree. this you can simply create by applying recursion in this function.
    int i,j;
    for (i=1; i<=h; i++)                \\\\ we are iterating it for every loop.
    {
        printlevels(root, i);           \\\\always calling the function with root node and their level for print.
        cout<<\"\ \";                     \\\\ To print in seprate line.
   }
}

The goal of this assignment is to reinforce the tree data structure in C++. Specifically, the assignment is to do the following: Construct a function that will

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site