POJ-2255 求二叉树

1.原题

链接: http://poj.org/problem?id=2255

Input

The input will contain one or more test cases.
Each test case consists of one line containing two strings preord and inord, representing the preorder traversal and inorder traversal of a binary tree. Both strings consist of unique capital letters. (Thus they are not longer than 26 characters.)
Input is terminated by end of file.

翻译:
输入将包含一个或多个测试用例。 每个测试用例由一行组成,其中包含两个字符串 preord 和 inord,表示二叉树的前序遍历和中序遍历。两个字符串都由唯一的大写字母组成。 (因此它们不超过 26 个字符。) 输入在文件末尾终止。

Output

For each test case, recover Valentine's binary tree and print one line containing the tree's postorder traversal (left subtree, right subtree, root).

翻译:
对于每个测试案例,恢复Valentine的二叉树,并打印一行字符表示该树的后序遍历(左子树、右子树、根)。
image

二叉树遍历的相关知识

先序遍历和中序遍历可以确定一颗树;后序遍历和中序遍历也可以确定一颗树
先序遍历:根左右
中序遍历:左根右
后序遍历:左右根
先序遍历的第一个字符以及后序遍历的最后一个字符就是二叉树的根节点
中序遍历中根节点的左侧为左子树,右侧为右子树

#include <iostream>
#include <cstring>
using namespace std;

char a1[30],a2[30];
int c, l1,l2;
void Tree(int i,int j){
    int k;
    char root;
    if (i > j)
        return ;
    root = a1[c++];//前序遍历的第一个字符就是二叉树的根节点
	//在中序遍历中找到根节点,其左边为左子树,右边为右子树
    for(k=i;k<=j;k++)
        if(root == a2[k])
            break;
    Tree(i,k-1);
    Tree(k+1,j);
    printf("%c",root);//左右根 后序遍历
}
int main(){
	//a1表示前序遍历,a2表示中序遍历
    while(~scanf("%s %s",a1,a2)){
        getchar();
        l2 = strlen(a2);
        c = 0;
        Tree(0,l2-1);
        printf("\n");
    }
    return 0;
}
posted @ 2022-09-26 15:26  之于尘  阅读(71)  评论(0)    收藏  举报