信管117118李志荣数据结构实验五

#include<iostream>
#include"head.h"
using namespace std;
int main()
{
	Binary<char> Tree;
	cout << "The PreOrder:" << endl;
	Tree.PreOrder();
	cout << "\nThe InOrder:" << endl;
	Tree.InOrder();
	cout << "\nThe PostOrder" << endl;
	Tree.PostOrder();
	cout << endl;
	Tree.PrintAll();
	Tree.PrintLeaf();
	return 0;
}

#include<iostream>
using namespace std;
template<typename DataType>
struct Node
{
	DataType data;
	Node *lchild, *rchild,*parent;
};
template<typename DataType>
class Binary
{
	private:
	Node<DataType> *root;
	Node<DataType>* Creat(Node<DataType> *bt, Node<DataType> *par) 
	{
		cout << "enter a data(# to quit): ";
		DataType ch;
		cin >> ch;
		if (ch == '#') bt = NULL;
		else
		{
			bt = new Node<DataType>;
			bt->data = ch;
			bt->parent = par;
			bt->lchild = Creat(bt->lchild, bt);
			bt->rchild = Creat(bt->rchild, bt);
		}
		return bt;
	}
	void Release(Node<DataType> *bt)
	{
		if (bt != NULL)
		{
			Release(bt->lchild);
			Release(bt->rchild);
			delete bt;
		}
	}
	void PreOrder(Node<DataType> *bt)
	{
		if (bt == NULL) return;		
		cout << bt->data << "  ";
		PreOrder(bt->lchild);
		PreOrder(bt->rchild);

	}
	void InOrder(Node<DataType> *bt)
	{
		if (bt == NULL) return;		
		PreOrder(bt->lchild);
		cout << bt->data << "  ";
		PreOrder(bt->rchild);
	
	}
	void PostOrder(Node<DataType> *bt)
	{
		if (bt == NULL) return;
		PreOrder(bt->lchild);
		PreOrder(bt->rchild);
		cout << bt->data << "  ";
		
	}
	void PrintAll(Node<DataType> *bt)
	{
		if (bt == NULL)return;
		cout << "the data:" << bt->data << "   ";
		if (bt->parent != NULL)
			cout << "the parent:" << bt->parent->data << "   ";
		else
			cout << "the parent is:NULL" << "   ";
		if (bt->lchild != NULL)
			cout << "the lchild:" << bt->lchild->data << "   ";
		else
			cout << "the lchild is:NULL" << "   ";
		if (bt->rchild != NULL)
			cout << "the rchild:" << bt->rchild->data << "   ";
		else
			cout << "the rchild is:NULL" << "   ";
		cout << endl;
		PrintAll(bt->lchild);
		PrintAll(bt->rchild);

	}
	void PrintLeaf(Node<DataType> *bt)
	{
		if (bt == NULL) return;
		if (bt->lchild == NULL&&bt->rchild == NULL)
		{
			cout << "the leaf:" << bt->data << endl;
		}
		PrintLeaf(bt->lchild);
		PrintLeaf(bt->rchild);
	}
public:
	Binary() { root = Creat(root, NULL); }
	~Binary() { Release(root); }
	void PreOrder() { PreOrder(root); }
	void InOrder() { InOrder(root); }
	void PostOrder() { PostOrder(root); }
	void PrintAll() { PrintAll(root); }
	void PrintLeaf() { PrintLeaf(root); }
};

猜你喜欢

转载自blog.csdn.net/rumple49/article/details/80355922