-
Please let me know how to deal with inputs of the form:
10 true 20 true 40 false false true 50 false false true 30 true 60 false false true 73 false false -
How to create BT if level order traversal is given
Doubt regarding input formats- Trees
-
for this you have to use recursion
node* buildTree(){ int d; cin>>d; node*nn=new node(d); string str; cin>>str; if(str=="true")nn->left=buildTree(); else nn->left=NULL; cin>>str; if(str=="true")nn->right=buildTree(); else nn->right=NULL; } -
for level order input you have to do in same manner as done in level order Traversal
node buildTree() {*
-
int d;* -
cin >> d;* -
node*root = new node(d);* -
queue<node*>q;* -
q.push(root);* -
while (!q.empty()) {* -
node*f = q.front();* -
q.pop();* -
cin >> d;* -
if (d != -1) {* -
f->left = new node(d); q.push(f->left);* -
}* -
else f->left = NULL;* -
cin >> d;* -
if (d != -1) {* -
f->right = new node(d); q.push(f->right);* -
}* -
else f->right = NULL;* -
}* -
return root;* - }*
1 Like
Please explain the second code
2nd one is same as levelorder traversal
have you done Levelorder Traversal if not then do that first
here i make a queue
initially push root to that
then i take input left and right child of current node and then also insert them to queue as well
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.