Facing problem in building the tree

how to build the tree using both data and key??

hi @rohitkandpal683
you are told that first root is given, then number of children (in preorder form, ie root, left, right). So for input
1 2
2 2
3 0
4 0
5 2
6 0
7 0
2

we make a root 1 and it has 2 children. we call function for left child.
root is 2 and it has 2 children. again calling for left child.
root is 3 and it has 0 children, so we dont call the function, and consequently return to the previous call. now we call for the right child of 2 and so on

I hope you are getting it now. If you are still confused let me know!

node* buildtree()
{
cin>>d>>k;
if(k==0)
{
return NULL;
}
node* root=new node(d);
root->left=buildtree();
root->right=buildtree();
}
what should i add in the above function to make it correct?? can you please share the code

@rohitkandpal683
https://ide.codingblocks.com/s/226676 you can see my approach here. Please note that this is not a complete program just a sample.

i understand it now, thanks for help.

1 Like