백준 9934 완전이진트리❌

CJB_ny·2023년 2월 21일
0

백준

목록 보기
81/104

완전 이진 트리


일단

  • 완전 이진 트리

    자식노드가 왼쪽부터 꽉차있는 트리

문제는 중위순회를 말하고있다. InOrder 30%

순회는 전위, 중위, 후위.

1 6 4 3 5 2 7있을 때 레벨화를 시켜야한다.

반으로 쪼개는 과정까지 생각을 했지만 그 이상 작업을 못함..

cpp 코드

#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <math.h>
#include <algorithm>
using namespace std;
#define endl "\n"
#define ll long long
const ll INF = 1e18;

vector<int> ret[14];
int n, a[1030];

void Go(int Start, int End, int Level)
{
    // Start 가 End보다 클 수 없다
    if (Start > End) return;

    if (Start == End)
    {
        ret[Level].push_back(a[Start]);
        return;
    }

    int Mid = (Start + End) / 2;
    ret[Level].push_back(a[Mid]);
    Go(Start, Mid - 1, Level + 1);
    Go(Mid + 1, End, Level + 1);
    return;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    cin >> n;
    int End = int(pow(2, n) - 1);
    for (int i = 0; i < End; ++i)
    {
        cin >> a[i];
    }

    Go(0, End, 1);

    for (int i = 1; i <= n; ++i)
    {
        for (int j : ret[i])
        {
            cout << j << " ";
        }
        cout << endl;
    }
   
    return 0;
}
profile
https://cjbworld.tistory.com/ <- 이사중

0개의 댓글