Sicily 1935. Rebuild the tree

題目大意:根據前序和中序重建二叉樹,並按bfs輸出

解體思路:關鍵注意重建二叉樹時遞歸判斷結束條件。bfs無難度。


// 1935. Rebuild the 2-tree 
#include <iostream>
#include <string>
#include <queue>

using namespace std;

string pre,mid;
int len,pos;

struct Node{
    char item;
    Node *left, *right;
    
    Node( char ch ){
        left = right = NULL;
        item = ch;
    }
};

void build( Node *&root, int begin, int end ){
    if( begin > end || pos >= pre.length() ) return;
    
    root = new Node(pre[pos]);
    int m = mid.find(pre[pos++]);
    build( root->left, begin, m-1 );
    build( root->right, m+1, end);
}

int main(){
    int m;
    cin >> m;
    
    while( m-- ){
        cin >> pre >> mid;
        len = pre.length();
        pos = 0;
        
        Node* root = new Node(pre[0]);
        build( root, 0, len-1 );    
        
        // bfs 
        queue<Node*> q;
        q.push(root);
        
        while( !q.empty() ){
            Node *curr = q.front();
            q.pop();
            
            cout << curr->item;
            if( curr->left ) q.push( curr->left );
            if( curr->right ) q.push( curr->right );
              
        }
        cout << endl;
    }
        
    return 0;     
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章