Tree 구현 연습

·2022년 12월 12일
0
#include <iostream>
#include <queue>
#include <stack>

namespace Cho
{
	struct Node
	{
		int Data;
		Node* LeftChild;
		Node* RightChild;
	};

	class tree
	{
	public:
		~tree();
		void Add(int _Data);
		void PrintPreorder() { PrintPreorder(Root); }
		void PrintInorder() { PrintInorder(Root); }
		void PrintPostorder() { PrintPostorder(Root); }
		void BFS(); 
		void DFS();

	private:
		void PrintPreorder(Node* _Node);
		void PrintInorder(Node* _Node);
		void PrintPostorder(Node* _Node);

	private:
		Node* Root;
	};

	tree::~tree()
	{
	}


	void tree::Add(int _Data)
	{
		Node* NewNode = new Node();
		NewNode->Data = _Data;

		Node* CurNode = Root;

		if (Root == nullptr)
		{
			Root = NewNode;
			return;
		}
		else
		{
			while (true)
			{
				if (CurNode->Data == _Data)
				{
					return;
				}

				else if (CurNode->Data > _Data)
				{
					if (CurNode->LeftChild != nullptr)
					{
						CurNode = CurNode->LeftChild;
					}

					else
					{
						CurNode->LeftChild = NewNode;
						return;
					}
				}

				else
				{
					if (CurNode->RightChild != nullptr)
					{
						CurNode = CurNode->RightChild;
					}

					else
					{
						CurNode->RightChild = NewNode;
						return;
					}
				}
			}
		}
	}

	void tree::BFS()
	{
		if (Root == nullptr)
		{
			return;
		}

		std::queue<Node*> NewQueue;
		NewQueue.push(Root);
		while (NewQueue.empty() == false)
		{
			std::cout << NewQueue.front()->Data << std::endl;
			if (NewQueue.front()->LeftChild != nullptr)
			{
				NewQueue.push(NewQueue.front()->LeftChild);
			}

			if (NewQueue.front()->RightChild != nullptr)
			{
				NewQueue.push(NewQueue.front()->RightChild);
			}
			NewQueue.pop();
		}
	}

	void tree::DFS()
	{
		if (Root == nullptr)
		{
			return;
		}

		std::stack<Node*> NewQueue;
		NewQueue.push(Root);
		while (NewQueue.empty() == false)
		{
			Node* CurNode = NewQueue.top();
			std::cout << CurNode->Data << std::endl;
			NewQueue.pop();
			if (CurNode->RightChild != nullptr)
			{
				NewQueue.push(CurNode->RightChild);
			}

			if (CurNode->LeftChild != nullptr)
			{
				NewQueue.push(CurNode->LeftChild);
			}
		}
	}

	void tree::PrintPreorder(Node* _Node)
	{
		if (_Node == nullptr)
		{
			return;
		}

		std::cout << _Node->Data << std::endl;
		PrintPreorder(_Node->LeftChild);
		PrintPreorder(_Node->RightChild);
	}

	void tree::PrintInorder(Node* _Node)
	{
		if (_Node == nullptr)
		{
			return;
		}

		PrintInorder(_Node->LeftChild);
		std::cout << _Node->Data << std::endl;
		PrintInorder(_Node->RightChild);
	}

	void tree::PrintPostorder(Node* _Node)
	{
		if (_Node == nullptr)
		{
			return;
		}

		PrintPostorder(_Node->LeftChild);
		PrintPostorder(_Node->RightChild);
		std::cout << _Node->Data << std::endl;
	}
}

0개의 댓글