Sicily 1935. 二叉树重建

来源:互联网 发布:社会主义建筑风格 知乎 编辑:程序博客网 时间:2024/05/06 16:17

根据前序遍历和中序遍历,求宽搜遍历结果。
容易知道的是,前序的第一个节点在中序中的位置可以将中序遍历的结果划分为左右子 树两个区间,同理第二个节点可以继续将左子树划分为左右子树两个区间……这样下去,当左边不再存在区间时,返回上一级,对另一半的区间进行划分,重复上述步骤,直到全部划分完毕。

这个过程可以用递归实现。另外,虽然题目说是二叉树重建,网上的代码也基本上重建了二叉树,但我觉得这挺麻烦的,就不重建了……

Run Time: 0sec

Run Memory: 312KB

Code length: 1916Bytes

SubmitTime: 2011-12-29 16:42:02

// Problem#: 1935// Submission#: 1150478// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/// All Copyright reserved by Informatic Lab of Sun Yat-sen University#include <iostream>#include <string>using namespace std;string s1, s2;int node, level[ 26 ];                                                         void build( int bot, int top, int n ) {    if ( bot <= top ) {                   node++;                     int i = bot;        while ( s1[ node ] != s2[ i ] )            i++;                                                                  level[ node ] = n;                                                    build( bot, i - 1, n + 1 );                                                                     build( i + 1, top, n + 1 );                                                                                }}                                                                                                                                                                          int main()                                               {                                                            int T;                                                      int i, j;                                                   int count, size;                                                                                                              cin >> T;                                                   while ( T-- ) {        cin >> s1 >> s2;        size = s1.size();                node = 0;        i = 0;        while ( s1[ node ] != s2[ i ] )            i++;        level[ node ] = 0;        build( 0, i - 1, 1 );        build( i + 1, size - 1, 1 );                count = 0;        for ( i = 0; count < size; i++ ) {            for ( j = 0; j < size; j++ ) {                if ( i == level[ j ] ) {                    cout << s1[ j ];                    count++;                }            }        }        cout << endl;    }        return 0;    }                                 


原创粉丝点击