How to construct the tree in this given scenario of input format.
We are not given number of nodes here.
Can you tell me to build the tree with preorder traversel?
Construct tree with given input
hello @poojas1607
construct the tree recursively by doing preorder traversal.
node * build(){
int data;
cin>>data;
node *root=new node(data);
cin>>data;
if(data!=-1)//check if left subtree exist or not
root->left=build()
cin>>data;
if(data!=-1)//check if right subtree exist or not
root->right=build()
}
How is this code working? Initally data is 3 so root node is created and then it inputs 3 and checks for -1 and if not we are again calling the build function but where does that 3 goes?
Sorry intially root is 8 and then we have 3.
check now->
the input give for this problem is bit different hence made some changes in build function
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.