转换二叉树

来源:互联网 发布:林弯弯的淘宝店 编辑:程序博客网 时间:2024/05/16 07:01

Description

DJ非常痴迷于数据结构,二叉树是他最喜欢的结构模型。这种每个顶点的度不大于2的简单的图总是能激发他的灵感。然而,二叉树的表示方法是一个困扰他已久的问题。如果用链表表示,不直观;画成图形,计算机又难以存储。好在他现在发现了一种既直观,计算机又便于存储的表示方法。该方法定义如下:

1、如果二叉树中节点X是叶子节点,则该节点直接表示为X。

2、如果二叉树中节点X有左子树,则该节点表示为(...)X,括号内为X的左子树。

3、如果二叉树中节点X有右子树,则该节点表示为X(...),括号内为X的右子树。

4、如果二叉树中节点X有左右子树,则该节点表示为(...)X(...),左边括号内为左子树,右边括号内为右子树。

现在DJ有许多二叉树的先序序列和中序序列,DJ要你写个程序帮他把这些二叉树转换为上述表示方法。

Input

输入第一行为一个整数N,表示有N个待转换的二叉树。

接下来有N行,每行由两个字符串组成,中间用空格分开。

每行的第一个字符串为二叉树的先序序列,第二个字符串为二叉树的中序序列。

输入字符串由大写字母组成,每个字母代表二叉树的一个节点,不会有两个相同的字母。

你可以假设不会输入无效数据。

 

Output

每组数据输出占一行,输出转换后的二叉树。

 

Sample Input

2

AB AB

ABCD BCAD

 

Sample Output

A(B)

(B(C))A(D)

 

#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node* tp;typedef struct node Node;struct node{char data;tp L_Child, R_Child;};void inorder(tp node) {if(!node)return;if(node->L_Child) {printf("(");inorder(node->L_Child);}if(node->L_Child)printf(")");printf("%c", node->data);if(node->R_Child) {printf("(");inorder(node->R_Child);}if(node->R_Child)printf(")");}tp create_tree(char* preorder, char* inorder, int n) {char* p, *q;int i, j, m;tp root;if(n <= 0)return NULL;root = (tp)malloc(sizeof(Node));root->data = preorder[0];root->L_Child = root->R_Child = NULL;i = 0;while(i < n) {if(preorder[0] == inorder[i])break;i++;}p = preorder + 1;q = inorder;root->L_Child = create_tree(p, q, i);p = preorder + i + 1;q = inorder + i + 1;root->R_Child = create_tree(p, q, n - i - 1);return root;}int main() {char pre[26], in[26];tp root = NULL;int nn;scanf("%d", &nn);while(nn--){scanf("%s%s", pre, in);free(root);root = create_tree(pre, in, strlen(in));inorder(root);printf("\n");}return 0;}


 

原创粉丝点击