根据前序和中序遍历构造二叉树

#include

typedef struct btnode
{
    char value;
    struct btnode *left;
    struct btnode *right;
}btnode;
int get_root_idx(char *preorder, char *inorder, int n)//返回根节点的序号
{
    int i;
    char ch;
    for(i=0, ch=preorder[0]; ivalue = root_val;                                                         //构造根节点
    root->left = build_from_preorder_and_inorder(preorder+1, inorder, i);           //处理左子树
    //处理右子树,可以想想当递归处理右子树的时候找到的i有没有问题?
    root->right = build_from_preorder_and_inorder(preorder+i+1, inorder+i+1, n-i-1);
    return root;
}
void postorder(btnode *root)  
{  
    if(root)  
    {  
        postorder(root->left);  
        postorder(root->right);  
        printf("%c", root->value);  
    }  
}  
int main()
{
    char *preorder = "ABDEGCFH";
    char *inorder = "DBEGAHFC";
    int n = strlen(preorder);
    btnode *root = build_from_preorder_and_inorder(preorder, inorder, n);
    postorder(root);
    printf("\n");
    return 0;
}


#include

typedef struct btnode
{
    char value;
    struct btnode *left;
    struct btnode *right;
}btnode;
int idxes_map[256];
void map_idxes(char *inorder, int n)
{
    int i;
    for(i=0; ivalue = root_val;                                                        
    root->left = build_from_preorder_and_inorder(preorder+1, inorder, i, offset);           
    root->right = build_from_preorder_and_inorder(preorder+i+1, inorder+i+1, n-i-1, offset+i+1);
    return root;
}
void postorder(btnode *root)
{
    if(root)
    {
        postorder(root->left);
        postorder(root->right);
        printf("%c", root->value);
    }
}
int main()
{
    char *preorder = "ABDEGCFH";
    char *inorder = "DBEGAHFC";
    int n = strlen(preorder);
    map_idxes(inorder, n);
    btnode *root = build_from_preorder_and_inorder(preorder, inorder, n, 0);
    postorder(root);
    printf("\n");
    return 0;
}


你可能感兴趣的:(C/C++)