알고리즘 문제/백준

1991 트리 순회 (트리 순회)[Silver I]

우대비 2024. 4. 21. 20:02
반응형
 

1991번: 트리 순회

첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파

www.acmicpc.net

 

 

트리 순회

트리 순회(Tree Traversal) 트리 자료구조 내의 모든 노드를 체계적으로 방문하는 과정을 말합니다 이러한 순회는 데이터의 구조적 특성을 분석하거나 특정 연산을 수행하기 위해 사용됩니다. 대표

flrjtwjrjt.tistory.com

 

#include <iostream>
#include <vector>

using namespace std;

static int N;

class Node
{
public:
	bool isRoot = false;
	Node* left;
	Node* right; 
	char c = ' ';

	void Preorder(vector<char>* result = new vector<char>())
	{
		// root
		result->push_back(c);

		if (left) 
			left->Preorder(result); 
		
		if (right)
			right->Preorder(result);

		if (isRoot) {
			for (char a : *result)
				cout << a;
			cout << "\n";
		}
	}

	void Inorder(vector<char>* result = new vector<char>())
	{

		if (left)
			left->Inorder(result);

		result->push_back(c);

		if (right)
			right->Inorder(result);

		if (isRoot) {
			for (char a : *result)
				cout << a;
			cout << "\n";
		}
	}

	void Postorder(vector<char>* result = new vector<char>())
	{
		if (left)
			left->Postorder(result);

		if (right)
			right->Postorder(result);

		result->push_back(c); 

		if (isRoot) {
			for (char a : *result)
				cout << a;
			cout << "\n";
		}
	} 


};

vector<Node> tree;
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> N;
	tree.resize(N);

	for (int i = 0; i < N; i++)
	{
		char root, left, right;
		cin >> root >> left >> right;
		int rootIndex = root - 'A';
		int leftIndex = left != '.' ? left - 'A' : -1;
		int rightIndex = right != '.' ? right - 'A' : -1;
		tree[rootIndex].c = root;

		if (leftIndex > 0) {
			tree[rootIndex].left = &tree[leftIndex];
			tree[rootIndex].left->c = left;
		}
		if (rightIndex > 0)
		{
			tree[rootIndex].right = &tree[rightIndex]; 
			tree[rootIndex].right->c = right;
		}
	} 
	tree[0].isRoot = true;

	tree[0].Preorder();
	tree[0].Inorder();
	tree[0].Postorder();

}
반응형
LIST