For binary tree: preorder and inoder can rebuild the binary tree, also preorder and postorder can rebuild binary tree
For binary search tree: preorder can rebuild binary search tree
int pre_idx=0;
tree* foo(int* arr_pre, int* arr_in, int in_idx_s, int in_idx_e)
{
if(in_idx_s>in_idx_e)
return NULL;
int in_idx=find_idx(arr_pre[pre_idx],arr_in, in_idx_s,in_idx_e);
tree* node=new tree;
node->val=arr_pre[pre_idx];
pre_idx++;
node->left=foo(arr_pre, arr_in,in_idx_s,in_idx-1);
node->right=foo(arr_pre,arr_in,in,in_idx+1,in_idx_e);
return node;
}
int find_idx(int pre_val,int in_arr[], int in_idx_s, int in_idx_e)
{
int idx=in_idx_s;
while(idx < in_idx_e)
{
if(pre_val==in_arr[idx])
return idx;
idx++;
}
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment