计蒜客 神奇的二叉树 ( 已知先序和中序遍历构建二叉树 )
思路: 题目要求输出在镜子里看到的二叉树 , 观察后可以发现 , 镜像的二叉树后序遍历实际上是先遍历右子树再遍历左子树再遍历根 , 所以只需要改一下后序遍历顺序即可.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_N 50
typedef struct Node {
char data;
struct Node *lchild , *rchild;
}Node;
Node* init(char data) {
Node *node = (Node*)malloc(sizeof(Node));
node->lchild = NULL; node->rchild = NULL;
node->data = data;
return node;
}
Node* build(char pre_str[] , char in_str[] , int len) {
Node *p = init(pre_str[0]);
int pos = strchr(in_str , pre_str[0]) - in_str;
if (pos > 0) {
p->lchild = build(pre_str + 1 , in_str , pos);
}
if (pos < len - 1) {
p->rchild = build(pre_str + pos + 1 , in_str + pos + 1 , len - pos - 1);
}
return p;
}
void postorder(Node *node) {
if (node->lchild != NULL) {
postorder(node->lchild);
}
if (node->rchild != NULL) {
postorder(node->rchild);
}
printf("%c",node->data);
}
void image_postorder(Node *node) {
if (node->rchild != NULL) {
image_postorder(node->rchild);
}
if (node->lchild != NULL) {
image_postorder(node->lchild);
}
printf("%c",node->data);
}
int main() {
char pre_str[MAX_N + 10] , in_str[MAX_N + 10];
scanf("%s %s",pre_str , in_str);
Node *root = build(pre_str , in_str , strlen(pre_str));
postorder(root);
printf("\n");
image_postorder(root);
printf("\n");
return 0;
}
如要转载请注明转载出处:http://www.cnblogs.com/WArobot