Doby's Lab

백준 13237번: Binary tree (C++) 본문

PS/BOJ

백준 13237번: Binary tree (C++)

도비(Doby) 2022. 7. 24. 23:30

https://www.acmicpc.net/problem/13237

 

13237번: Binary tree

A binary tree is a mathematical structure made of nodes where each node can have up to two children nodes. One child node will be called left child and the other right child. ch If node B is a child node of A, then we say that A is the parent node of B. In

www.acmicpc.net


Solved By: DFS

 

 

#include <iostream>
#include <vector>
#define MAX 21
using namespace std;

int n;
vector<int> adj[MAX];
int level[MAX];
int root;

void dfs(int now){
    for(int i = 0; i < adj[now].size(); i++){
        int next = adj[now][i];
        level[next] = level[now] + 1;
        dfs(next);
    }
}

int main(){
    cin >> n;
    for(int i = 1, v; i <= n; i++){
        cin >> v;
        if(v == -1) root = i;
        else adj[v].push_back(i);
    }
    
    dfs(root);
    for(int i = 1; i <= n; i++) cout << level[i] << '\n';
    return 0;
}

 

728x90