标签:
ACBFGED ABCDEFG CDAB CBAD
DBACEGF BCAD
这道题主要考查对二叉树的遍历的熟悉程度,对先序遍历,中序遍历,后序遍历的掌握程度;
由后序遍历可以得到,最后一个字母应该就是树的根节点,中序遍历是先访问左子树,后访问根节点,在访问右子树,然后通过中序遍历的序列,可以把这颗树分成左右子树,得出这颗树的结构,然后再递归得出先序遍历的序列
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Node { char value; Node* left; Node* right; }; Node* buildNode(char value) { Node* node = (Node*)malloc(sizeof(Node)); node->value = value; node->left = node->right = NULL; return node; } Node* rebuildTree(char* post, char* in, int len) { int i = 0; if(len == 0) return NULL; Node* head = buildNode(post[len-1]); for(i = 0; i < len; i++) { if(in[i] == post[len - 1]) break; } head->left = rebuildTree(post, in, i); head->right = rebuildTree(post+i, in+i+1, len-i-1); return head; } void preorder(Node* head) { if(head == NULL) return; printf("%c", head->value); preorder(head->left); preorder(head->right); } int main() { char post[100], in[100]; while(scanf("%s%s", post, in) != EOF) { preorder(rebuildTree(post, in, strlen(post))); printf("\n"); } return 1; }
标签:
原文地址:http://www.cnblogs.com/sdlwlxf/p/4557344.html