# 根据前序遍历和中序遍历结果恢复二叉树

### 思路

# include <cstdio>
using namespace std;
/**************************/
struct Node{
char v;
Node * left;
Node * right;
} * root;

void init() {
root = NULL;
}

Node * create_node(char v){
Node * p = new Node;
p->v = v;
p->left = NULL;
p->right = NULL;
return p;
}

Node * reConstructTree(char pre[], int pl, int pr, char in[], int il, int ir) {
if (pl > pr) return NULL;
else if (pl == pr) return create_node(pre[pl]); // 只有一个节点

char spc = pre[pl];
for (int i=il; i<=ir; i++) {
if (spc == in[i]) {
// 划分左右子树
int offset = i-il;
Node * l = reConstructTree(pre, pl+1, pl+offset, in, il, i-1);
Node * r = reConstructTree(pre, pl+offset+1, pr, in, i+1, ir);
// 新建节点，指向左右子树
Node * p = create_node(spc);
p->left = l;
p->right = r;
return p;
}
}
return NULL; //出错
}

//中序遍历
void inOrder(Node * p) {
if (p == NULL) return;
inOrder(p->left);
printf("%c-", p->v);
inOrder(p->right);
}

int main() {
init();
char pre[] = "123456";
char in[] = "324165";
root = reConstructTree(pre, 0, 5, in, 0, 5);
inOrder(root);
return 0;
}

posted @ 2019-06-25 10:11  happy_codes  阅读(241)  评论(0编辑  收藏