vidigummy KAU/재활운동

재활운동3(이진트리)

vidi 2020. 6. 10. 14:00

어우.. 끔찍하다.. 나 진짜 나쁘지 않은 학생이었구나...

#include <iostream>

using namespace std;

class Node
{
	friend class Tree;
private:
	int data;
	Node* Left;
	Node* Right;
public:
	Node(int val = NULL);
};

class Tree
{
private:
	Node* root;
	void add(Node* root = NULL, int val = NULL);
	void visit(Node* current);
	void inorder(Node* current);
	void preorder(Node* current);
public:
	Tree();
	void PrintAll();
	void MakeTreeFromLine();
	Node* g();
};

Node::Node(int val)
{
	data = val;
	Left = NULL;
	Right = NULL;
}

Tree::Tree()
{
	root = NULL;
}

void Tree::add(Node* root, int val)
{
	Node* n1 = new Node(val);
	if (this->root == NULL)
	{
		this->root = n1;
	}
	else
	{
		if (root->data > val)
			if (root->Left == NULL)
				root->Left = n1;
			else
				add(root->Left, val);
		else
			if (root->Right == NULL)
				root->Right = n1;
			else
				add(root->Right, val);
	}
}

void Tree::visit(Node* current)
{
	cout << current->data << " ";
}

void Tree::inorder(Node* current)
{
	if (current != NULL)
	{
		inorder(current->Left);
		visit(current);
		inorder(current->Right);
	}
}

void Tree::preorder(Node* current)
{

	if (current != NULL)
	{
		visit(current);
		preorder(current->Left);
		inorder(current->Right);
	}
}

void Tree::PrintAll()
{
	cout << "Inorder.\n";
	this->inorder(this->root);
	cout << "\nㅋ";
	this->preorder(this->root);
	cout << "\n끝";
}

Node* Tree::g()
{
	return this->root;
}

void Tree::MakeTreeFromLine()
{
	int tmp;
	for (int i = 0; i < 6; i++)
	{
		cin >> tmp;
		add(this->root, tmp);
	}
}

int main()
{
	Tree T1 = Tree();
	T1.MakeTreeFromLine();
	T1.PrintAll();
}