前序和中序构造二叉树

前序和中序、后序和中序序列可以构造唯一一颗二叉树.
1.从前序序列找到父节点,即首个结点;
2.中序序列找到此父结点,它的左右分别对应左孩子和右孩子;
以此递归,直到满足边界值.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<stack>
#include<queue>
using namespace std;

typedef char DATA_TYPE;

typedef struct node
{
DATA_TYPE data;
node *lch, *rch;
node()
{
lch = rch = 0;
}
} Node;

void print(Node *r)
{
if(r)
{
print(r->lch);
printf("%c", r->data);
print(r->rch);
free(r);
}
}

Node *buildTree(char *pre, int idxStart, int idxEnd, char *mid, int idxS, int idxE)
{
if(idxStart==idxEnd || idxS >= idxE) return NULL;
int i = idxS;
Node *node = (Node*)malloc(sizeof(Node));
node->data=pre[idxStart];
node->lch=node->rch=NULL;
for(; i<idxE; i++)
{
if(pre[idxStart] == mid[i])break;
}

if(i==idxEnd)
{
return buildTree(pre, idxStart+1, idxEnd, mid, idxS, idxE);
}
else
{
node->lch = buildTree(pre, idxStart+1, idxEnd, mid, idxS, i);
node->rch = buildTree(pre, idxStart+1, idxEnd, mid, i+1, idxE);
}
return node;
}

int main()
{
DATA_TYPE preOrderTraversal[] = "abdejcfig";
DATA_TYPE inOrderTraversal[] = "dbjeaficg";
Node *root = buildTree(preOrderTraversal, 0, 9, inOrderTraversal, 0, 9);
print(root);
return 0;
}