码迷,mamicode.com
首页 > 其他好文 > 详细

根据二叉树的先序和中序遍历重建二叉树

时间:2014-11-04 17:23:37      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   os   for   sp   2014   log   ef   

#include <iostream>
#include <cstdio>
using namespace std;
typedef struct BiTNode {
    int data;
    struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

BiTree PreInCreate(char A[], char B[], int l1, int h1, int l2, int h2) {
    BiTNode *root = (BiTNode *)malloc(sizeof(BiTNode));
    root->data = A[l1];
    int i;
    for(i = l2; B[i] != root->data; i++);
    int llen = i - l2;
    int rlen = h2 - i;
    if(llen){
        root->lchild = PreInCreate(A, B, l1+1, l1+llen, l2, l2+llen-1);
    } else {
        root->lchild = NULL;
    }
    if(rlen) {
        root->rchild = PreInCreate(A, B, h1-rlen+1, h1, h2-rlen+1, h2);
    } else {
        root->rchild = NULL;
    }
    return root;
}
void PreOrder(BiTree T) {
    if(T != NULL) {
        printf("%c  ", T->data);
        PreOrder(T->lchild);
        PreOrder(T->rchild);
    }
}
void InOrder(BiTree T) {
    if(T != NULL) {
        InOrder(T->lchild);
        printf("%c  ", T->data);
        InOrder(T->rchild);
    }
}

int main()
{
    char A[100], B[100];
    printf("please input preorder and inorder :\n");
    scanf("%s%s", A+1, B+1);
    A[0] = A[0] = 'a';
    int len = strlen(A)-1;
    BiTNode * root = PreInCreate(A, B, 1, len, 1, len);
    PreOrder(root);
    cout << endl;
    InOrder(root);

    return 0;
}
/**
Test:
124356
421536
**/

根据二叉树的先序和中序遍历重建二叉树

标签:blog   io   ar   os   for   sp   2014   log   ef   

原文地址:http://blog.csdn.net/achiberx/article/details/40787853

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!