Facebook Interview Question
Software Engineer / DevelopersThis line doesn't look correct to me:
cur.right = buildTreePreorder(cur.left.index + 1);
It should be:
cur.right = buildTreePreorder(cur.index + number of nodes in the left subtree + 1);
is it possible?
A
B
CD
and
A
BD
C
preorder and marks are all the same:
(A,N)(B,N)(C,L)(D,L)
Node* formtree(char *preorder, int &num)
{
if(preorder[num]=='\0') return NULL;
Node *t=new Node();
if(preorder[num++]=='L')
{
t->left=t->right=NULL;
}
else
{
t->left=formtree(preorder,num);
t->right=formtree(preorder,num);
}
return t;
}
Would you mind to explain the idea first? It helps others to see what you are doing here. Thanks.
its the other way to ask the same question in which given the preorder of tree & construct the tree with preorder..isn't it you may wants to look @ this & can modify if need to achieve answer
http dot shashank7s dot blogspot dot com/2011/03/special-type-of-tree-is-given-where-all dot html
correct me if anything wrong
If we assume that tree nodes either have 0 or 2 nodes, then the tree constructed should be unique. Build the tree in recursion just like a preorder traverse.
- yyl September 08, 2011