Vipul Sinha - 1 month ago 7

C++ Question

I am supposed to take input of a binary tree recursively as :

10 true 20 true 40 false false true 50 false false true 30 true 60 false false true 73 false false

so the tree created should be:-

`10`

20 30

40 50 60 73

I have created a function which cannot create this tree, whats wrong in the code?

`node* takeInput() {`

int data;

string a;

cin>>data>>a;

node*n = NULL;

if(a=="true") {

n = new node(data);

n->left = takeInput();

n->right = takeInput();

}

if(a=="false") {

return NULL;

}

return n;

}

Answer Source

Take the input as inorder tree traversal...

- First Take input for the root node.
- Then take input for left subtree if exists.
- Then take input for right subtree if exists.

Code:

```
void takeInput(Node* &node) {
string left, right;
int data;
cin >> data; // input for root node
node = new Node(data);
cin >> left;
if(left == "true") {
takeInput(node->left); // taking input for left subtree
}
cin >> right;
if(right == "true") {
takeInput(node->right); // taking input for right subtree
}
}
Node* InputBinaryTree() {
Node *root;
takeInput(root);
return root;
}
```