Sicily 1935. 二叉树重建

本文介绍了一种利用前序遍历和中序遍历结果来实现二叉树的宽度优先搜索遍历的方法。通过递归算法确定每个节点的位置,并记录它们的层级,最后按层级顺序输出所有节点。

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

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

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;
    
}                                 


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值