由中序遍历序列和后序遍历序列构造二叉树(递归实现)

#include <stdio.h>
#include <string.h>

typedef struct bitree_node
{
    char data;
    struct bitree_node * lchild, * rchild;
}bitree_node, *binary_tree;


int locate_data( char arr[], int left, int right, char key )
{
    int i;
    for( i = left; i <= right; ++i )
    {
        if( arr[i] == key )
            break;
    }
    return i;
}

void create_bitree_from_post_in_order( 
        char post_order[],  // postorder traversal sequence
        char in_order[],    // inorder traversal sequence
        int left,           // start index in inorder sequence
        int right,          // end index in inorder sequence
        int pos,            // index of root in postorder sequence
        binary_tree * root )
{
    int idx;
    bitree_node * p = ( bitree_node * )malloc( sizeof( bitree_node ) );
    p->data = post_order[pos];
    idx = locate_data( in_order, left, right, p->data );

    // create left subtree recursively
    create_bitree_from_post_in_order( post_order, in_order, 
            left, idx - 1, pos - 1 - ( right - idx ), &p->lchild );
    
    // create right subtree recursively
    create_bitree_from_post_in_order( post_order, in_order,
            idx + 1, right, pos - 1, &p->rchild );
    *root = p;
}


int main()
{
    char post_order[] = "cbfhgeda";
    char in_order[] = "cbafehgd";
    create_bitree_from_post_in_order( post_order, in_order, 0, 8, 8 );
    return 0;
}

 

你可能感兴趣的:(c,struct,tree,include,traversal)