珍爱生命,多用python
一道二叉树重建的问题,用C被折磨得不轻,干脆用python做了,一切清爽了不少。
问题:输入二叉树的前序与中序,输出二叉树的后序
本文章来自博客园,如果在别的地方看可能是本人的博客同步
代码
1 C代码
#include<stdio.h> #include<stdlib.h> #include<string.h> const int MAXN = 256; typedef struct TNode{ int have_value; int v; struct TNode* left, *right; } Node; Node* root; char s[MAXN + 10]; int failed; int n = 0, ans[MAXN]; Node* newnode() { Node* u = (Node*) malloc(sizeof(Node)); if(u != NULL) { u->have_value = 0; u->left = u->right = NULL; } return u; } void addnode(int v, char* s) { int n = strlen(s); Node* u = root; for(int i = 0; i < n; i++) if(s[i] == 'L') { if(u->left == NULL) u->left = newnode(); u = u->left; } else if(s[i] == 'R') { if(u->right == NULL) u->right = newnode(); u = u->right; } if(u->have_value) failed = 1; u->v = v; u->have_value = 1; } void remove_tree(Node* u) { if(u == NULL) return; remove_tree(u->left); remove_tree(u->right); free(u); } int read_input() { failed = 0; remove_tree(root); root = newnode(); for(;;) { if(scanf("%s", s) != 1) return 0; if(!strcmp(s, "()")) break; int v; sscanf(&s[1], "%d", &v); addnode(v, strchr(s, ',')+1); } return 1; } int bfs() { int front = 0, rear = 1; Node* q[MAXN]; q[0] = root; while(front < rear) { Node* u = q[front++]; if(!u->have_value) return 0; ans[n++] = u->v; if(u->left != NULL) q[rear++] = u->left; if(u->right != NULL) q[rear++] = u->right; } return 1; } int main() { while(read_input()) { if(!bfs()) failed = 1; if(failed) printf("-1\n"); else { for(int i = 0; i < n; i++) printf("%d ", ans[i]); printf("\n"); } } return 0; }
2 python 代码
ans = [] def show_posorder(perorder, inorder): if(len(perorder) == 0 and len(inorder) == 0): return 1 else: ans.extend(perorder[0]) ir = inorder.index(perorder[0]) show_posorder(perorder[1:ir+1], inorder[0:ir]); show_posorder(perorder[ir+1:], inorder[ir+1:]); print ans.pop(), def input(): perorder = raw_input("input the perorder:") inorder = raw_input("input the inorder:") show_posorder(perorder, inorder)
Date: 2011-10-17 20:07:42 CST
HTML generated by org-mode 6.21b in emacs 23