본문 바로가기

Algorithm/BAEKJOON

[BOJ] 1068번 트리 (C++)

728x90
반응형

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

 

1068번: 트리

첫째 줄에 트리의 노드의 개수 N이 주어진다. N은 50보다 작거나 같은 자연수이다. 둘째 줄에는 0번 노드부터 N-1번 노드까지, 각 노드의 부모가 주어진다. 만약 부모가 없다면 (루트) -1이 주어진다

www.acmicpc.net

 

#include <iostream>
#include <vector>
using namespace std;

vector<int> tree[50];
int n, k, root;
int leafcnt = 0;

int dfs(int node){
	if(node == k) return -1;
	if(tree[node].size() == 0){
		leafcnt++;
		return 0;
	}
	for(int i = 0; i < tree[node].size(); i++){
		int tmp = dfs(tree[node][i]);
		if(tmp == -1 && tree[node].size() == 1) leafcnt++;
	}
	return 0;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	cin >> n;
	for(int i = 0; i < n; i++){
		int p;
		cin >> p;
		if(p == -1) root = i;
		else tree[p].push_back(i);
	}
	cin >> k;
	dfs(root);
	cout << leafcnt;
	return 0;
}

 

리프 노드인 경우

1. 자식 노드가 없음

2. 자식 노드가 하나인데 그 자식 노드가 제거됨

728x90
반응형