본문 바로가기

프로그래밍/c++

c++ 템플릿, 트리(미완)

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

template <class K>
class node {
public:
	node * left;
	node * right;
	node(K val, node* left, node* right) : val(val), left(left), right(right) {};
private:
	K val;
};

template <class K>
class tree {
	friend class node<K>;
public:
	node<K> * root;
	void inorder(node<K> * curr);
	void preorder(node<K> * curr);
	void postorder(node<K> * curr);
};

template <class K>
void tree<K>::inorder(node<K> * curr) {
	if (curr == NULL) return;

	inorder(curr->left);
	cout << curr->val << " ";
	inorder(curr->right);
}

template <class K>
void tree<K>::preorder(node<K> * curr) {
	if (curr == NULL) return;

	cout << curr->val << " ";
	preorder(curr->left);
	preorder(curr->right);
}

template <class K>
void tree<K>::postorder(node<K> * curr) {
	if (curr == NULL) return;

	postorder(curr->left);
	postorder(curr->right);
	cout << curr->val << " ";
}

int main() {

	tree<int> mytree;
	node<int> node1(1, NULL, NULL);
	node<int> node2(2, NULL, NULL);
	node<int> node3(3, NULL, NULL);
	node<int> node4(4, NULL, NULL);

	mytree.root = &node1;
	mytree.root->right = &node2;
	mytree.root->left = &node3;
	mytree.root->right->right = &node4;

	/*

	1
	3 2
	4

	*/

	mytree.inorder(mytree.root);
	cout << endl;
	mytree.preorder(mytree.root);
	cout << endl;
	mytree.postorder(mytree.root);
	while (1) {}
}

'프로그래밍 > c++' 카테고리의 다른 글

c++ 템플릿, 트리(미완)  (0) 2019.08.27
c++ 클래스  (0) 2019.08.27
C++ I/O 속도 문제  (0) 2018.10.14
Visual Studio 에서 scanf, printf 사용하기  (0) 2018.06.03
make, premake4 실험실  (0) 2018.05.04
c++ 실험실  (0) 2018.05.04