Solved programming problem

Implement Tree in C++.

Source code

#include <iostream>

using namespace std;

struct tree

{

    char data;

    struct tree *right,*left;

};

typedef struct tree node;

node *head=NULL;

void inorderprint(node *root)

{

    if(root->left!= NULL)

    {

        inorderprint(root->left);

    }

    cout<<root->data<<" ";

    if(root->right!= NULL)

    {

        inorderprint(root->right);

    }

}

void createtree(node *root)

{

    int ans;

    cout<<root->data<<" Has Any Left Child? 1/0: ";

    cin>>ans;

    if(ans==1)

    {

        root->left = new node();

        cin>>root->left->data;

        createtree(root->left);

    }

    else

    {

        root->left = NULL;

    }

    cout<<root->data<<" Has Any Right Child? 1/0: ";

    cin>>ans;

    if(ans==1)

    {

        root->right = new node();

        cin>>root->right->data;

        createtree(root->right);

    }

    else

    {

        root->right = NULL;

    }

}

int main()

{

    node *root = new node();

    cout<<"Root :"<<endl;

    cin>>root->data;

    createtree(root);

    cout<<"
Tree In Order: ";

    inorderprint(root);

    cout<<endl;

    return 0;

}

Output

Root :
1
1 Has Any Left Child? 1/0: 1
2
2 Has Any Left Child? 1/0: 0
2 Has Any Right Child? 1/0: 0
1 Has Any Right Child? 1/0: 1
3
3 Has Any Left Child? 1/0: 0
3 Has Any Right Child? 1/0: 0

Tree In Order: 2 1 3

 

Join the discussion

Add your comment