Microsoft | Coding
From careercup by sarthak
Given a preorder and inorder traversal of a binary tree, can you reproduce the tree? If yes, then write a function using C/C ++ that builds the tree and returns the root node of the tree.
# Include <stdio. h>
# Include <iostream>
# Include <stack>
# Include <windows. h>
# Include <string>
Using namespace STD;
# Define check (x) {If (! (X) {printf ("Fatal error:" # X); exit (0 );}}
Void trace (char * szformat ,)
{
Va_list L;
Char s [500];
Va_start (L, szformat );
Vsprintf (S, szformat, L );
Outputdebugstringa (s );
}
Typedef class bitnode
{
Public:
Char data;
Bitnode * LC, * RC;
} * Bitree;
// Create a binary tree in the first and middle orders
/**//*********************************** *************************************/
/** // * Microsoft | Coding
From careercup by sarthak
Given a preorder and inorder traversal of a binary tree, can you reproduce the tree?
If yes, then write a function using C/C ++ that builds the tree and returns the root node of the tree .*/
/**//*********************************** *************************************/
Bitree bitreecreate (string prestr, string instr)
{
Check (prestr. Size () = instr. Size () & instr. Size ()> 0 );
Char c = prestr [0];
Int Pos = instr. find_first_of (C );
Check (Pos! =-1 );
Bitree P = new bitnode;
P-> DATA = C;
If (Pos = 0)
P-> lc = 0;
Else
{
String ins1 = instr. substr (0, POS );
String PreS1 = prestr. substr (1, POS );
Trace ("ins1: % s, PreS1: % s", ins1.c _ STR (), pres1.c _ STR ());
P-> lc = bitreecreate (PreS1, ins1 );
}
If (Pos = prestr. Size ()-1)
P-> rc = 0;
Else
{
String ins2 = instr. substr (Pos + 1 );
String preS2 = prestr. substr (1 + POS );
Trace ("ins2: % s, PreS2: % s", ins2.c _ STR (), pres2.c _ STR ());
P-> rc = bitreecreate (PreS2, ins2 );
}
Return P;
}
Void traverseinorder2 (bitree T)
{
If (t)
{
Traverseinorder2 (t-> Lc );
Cout <t-> data;
Traverseinorder2 (t-> RC );
}
}
// First-order traversal
Void traverse1order (bitree T)
{
If (t)
{
Cout <t-> data;
Traverse1order (t-> Lc );
Traverse1order (t-> RC );
}
}
Void test ()
{
Bitree tree = bitreecreate ("abdecfg", "dbeafcg ");
Cout <"preorder:" <Endl;
Traverse1order (tree );
Cout <Endl <"inorder:" <Endl;
Traverseinorder2 (tree );
Cout <Endl;
}