중차 역행 시퀀스와 후차 역행 시퀀스로 두 갈래 트리 구성 (역귀 실현)

#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;
}

좋은 웹페이지 즐겨찾기