DMOJ · coci13c5p2

COCI '13 Contest 5 #2 Obilazak

This C++ solution uses simulation for DMOJ coci13c5p2 COCI '13 Contest 5 #2 Obilazak. Read the reasoning, inspect the code, or try your own test case below.

coci13c5p2Graphs & treesSimulationC++46 lines
Solution159of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Simulation

title is Obilazak; it gives a perfect binary tree's inorder entrance sequence and asks for nodes by level, exactly as reconstructed.

Graphs & trees

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

perfect_binary_tree.cpp

C++

    #include <bits/stdc++.h>
     
    using namespace std;
     
    struct Node {
        int val;
        Node* left;
        Node* right;
        Node(int v) : val(v),left(nullptr), right(nullptr){}
     
    };
    int height, indx;
    vector<int> seq;
    Node* build(int depth){
        if(depth > height) return nullptr;
        Node* root = new Node(0);
        root->left = build(depth + 1);
        root->val = seq[indx++];
        root->right = build(depth + 1);
        return root; 
    }
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        cin >> height;
        int total = (1 << height) - 1;
        seq.resize(total);
        for(int i = 0; i < total; i++){
            cin >> seq[i];
        }
        indx = 0;
        Node* root = build(1);
        queue<Node*> q;
        q.push(root);
        priority_queue<int> pq;
        while(!q.empty()){
            int size = q.size();
            for(int i = 0; i < size; i++){
                Node* cur = q.front(); q.pop();
                cout << cur->val << (i == size - 1 ? "\n" : " ");
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);
            }
        }
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.