PAT(A) - 1119. Pre- and Post-order Traversals

22 篇文章 0 订阅


Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences, or preorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.

Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first printf in a line "Yes" if the tree is unique, or "No" if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input 1:
7
1 2 3 4 6 7 5
2 6 7 4 5 3 1
Sample Output 1:
Yes
2 1 6 4 7 3 5
Sample Input 2:
4
1 2 3 4
2 4 3 1
Sample Output 2:
No
2 1 3 4

思路分析:根据前序和后序建立二叉树。结果可能不唯一。明天考试加油!


#include <cstdio>
#include <cstdlib>
#include <vector>
#include <stack>

#define MAX 30

typedef struct node {
    int data;
    struct node *lchild;
    struct node *rchild;
} Node;

using namespace std;

int pre[MAX];       // 前序序列
int post[MAX];      // 后序序列
int visit[MAX];     // 后序序列的访问标记
vector<int> vec;    // 保存中序序列

bool flag = true;   // 判断是否唯一

int findPostRoot( int start, int n ) {
    for( int i = start; i < n; i++ ) {
        if( visit[i] == 1 ) {
            return i;
        }
    }
}

int findFromPost( int val, int n ) {
    for( int i = 0; i < n; i++ ) {
        if( val == post[i] ) {
            return i;
        }
    }
}

// 利用栈查找目标val的结点指针
Node *findPreRoot( Node *curNode, int val ) {
    Node* p = NULL;
    stack<Node*> s;
    s.push( curNode );
    while( !s.empty() ) {
         Node *top = s.top();
         s.pop();
         if( top->data == val ) {
             p = top;
             break;
         }
         if( top->lchild != NULL ) s.push( top->lchild );
         if( top->rchild != NULL ) s.push( top->rchild );
    }
    return p;
}

// 建立二叉树,返回根结点
Node *BuildTree( int n ) {
    Node *root = NULL;
    root = ( Node* )malloc( sizeof( Node ) );
    root->lchild = NULL;
    root->rchild = NULL;
    root->data = pre[0];    // 根结点是pre[0],就是前序序列的第一个元素
    visit[n - 1] = 1;       // visit是后序序列的访问标记,根结点是后序序列最后一个元素,故置一

    // 遍历前序序列,插入每个新的结点
    for( int i = 1; i < n; i++ ) {
        //printf( "准备插入%d\n", pre[i] );
        int idInPost = findFromPost( pre[i], n );   // 寻找前序序列第i个元素在后序序列中的位置idInPost
        int postRoot = findPostRoot( idInPost, n ); // 寻找待插入结点的父亲结点元素在后序序列中的下标
                                                    // 就是visit从左往右遍历,第一个是visit[i] = 1的下标

        //printf( "寻找%d\n", post[postRoot] );
        Node *preRoot = findPreRoot( root, post[postRoot] );   // 在二叉树中查找其父亲结点指针
        Node *p = ( Node* )malloc( sizeof( Node ) );           // 新分配给待插入结点一个空间
        p->lchild = NULL;
        p->rchild = NULL;
        p->data = pre[i];

        if( postRoot - idInPost > 1 ) {         // 如果下标相减大于1,肯定是插入到左边
            preRoot->lchild = p;
            //printf( "%d插入到左边\n", pre[i] );
        }
        else if( postRoot - idInPost == 1 ) {   // 如果下标相减恰好等于1
            if( preRoot->lchild != NULL ) {     // 如果其父结点已经有左孩子了,那肯定是插入到右边
                preRoot->rchild = p;
            }
            else {                              // 如果其父结点左孩子不存在,这时候就是不唯一的情况
                flag = false;                   // 令flag = false
                preRoot->lchild = p;            // 默认插入到右边,插入到左边也可以的。
            }
            //printf( "%d插入到右边\n", pre[i] );
        }
        visit[idInPost] = 1;                    // 访问标记置1
    }
    return root;
}

// 中序遍历
void InOrder( Node *curNode ) {
    if( curNode == NULL ) return;
    InOrder( curNode->lchild );
    //printf( "%d ", curNode->data );
    vec.push_back( curNode->data );
    InOrder( curNode->rchild );
}

// 打印结果
void PrintResult() {
    for( int i = 0; i < vec.size(); i++ ) {
        if( i == 0 ) printf( "%d", vec[i] );
        else printf( " %d", vec[i] );
    }
}

int main() {
    //freopen( "123.txt", "r", stdin );
    int n;
    scanf( "%d", &n );

    for( int i = 0; i < n; i++ ) scanf( "%d", &pre[i] );
    for( int i = 0; i < n; i++ ) scanf( "%d", &post[i] );

    Node *root = NULL;      // 根节点
    root = BuildTree( n );  // 建树
    InOrder( root );        // 中序序列
    printf( "%s\n", flag ? "Yes" : "No" );
    PrintResult();
    printf( "\n" );        // 最后要加一个换行,要不然提示格式错误
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值