According to the order and the order before reconstructing binary tree
#include
#include
using namespace std;
Typedef struct TreeNode {
Int val.
TreeNode * left;
TreeNode * right;
TreeNode (int x) : val (x), left (NULL), right (NULL) {}
};
TreeNode * reConstructBinaryTree (vector
{
If (pre. The size ()==0)
return NULL;
Root TreeNode *=new TreeNode (pre [0]).
int i;
For (I=0; i
Vector
Int pre_i=1;
For (int j=0; J & lt; In the size (); J++)
{
If (j & lt; I)
{
In_left. Push_back (in [j]);//sequence traversal left subtree sequence through the array
Pre_left. Push_back (pre [pre_i]);//before sequence traversal sequence through the array before left subtree
Pre_i + +;
}
Else if (j & gt; I)
{
In_right. Push_back (in [j]);
Pre_right. Push_back (pre [pre_i]);
Pre_i + +;
}
}
Root - & gt; Left=reConstructBinaryTree (pre_left in_left);
Root - & gt; Right=reConstructBinaryTree (pre_right in_right);
Return the root;
}
Int main ()
{
Vector
The pre. Resize (1000);
The pre. Push_back (1);
The pre. Push_back (2);
The pre. Push_back (4);
The pre. Push_back (7);
The pre. Push_back (3);
The pre. Push_back (5);
The pre. Push_back (6);
The pre. Push_back (8);
Vector
In the resize (1000);
In the push_back (4);
In the push_back (7);
In the push_back (2);
In the push_back (1);
In the push_back (5);
In the push_back (6);
In the push_back (8);
In the push_back (6);
Root TreeNode *=reConstructBinaryTree (pre, in);
system("pause");
}