二叉排序树::c++模板实现::泛型类,只要能排序,我就可以排的二叉树!

只要再有一个可以排序的类就可以直接使用这个二叉排序树,完全可重用性MAX

#include<iostream>
using namespace std;
template<class T>
class Node {
public:
	T val;
	int ln, rn;
	Node<T> *h;
	Node<T> *l;
	Node<T> *r;
	Node<T>(T value,Node *head) {
		this->val = value;
		this->h = head;
		this->l = nullptr;
		this->r = nullptr;
	}
};
template<class T>
class Tree {
public:
	Node<T> *root, *temp;
	Tree() {
		root = nullptr;
		temp = nullptr;
	}
	void add(T v) {
		if (root == nullptr) {
			root = new Node<T>(v, nullptr);
		}
		else {
			temp = root;
			while (true) {
				if (temp->val > v) {
					if (temp->l != nullptr) {
						temp = temp->l;
					}
					else {
						temp->l = new Node<T>(v, temp);
						return;
					}
				}
				else {
					if (temp->r != nullptr) {
						temp = temp->r;
					}
					else {
						temp->r = new Node<T>(v, temp);
						return;
					}
				}
			}
		}
	}
	void cut(T t) {
		temp = root;
		Node<T> *c;
		if (temp->val == t) {
			if (root->r!=nullptr) {
				root = temp->r;
				c = temp->r;
				temp = temp->l;
				while (c->l != nullptr) {
					c = c->l;
				}
				c->l = temp;
			}
			else if (root->l != nullptr) {
				root = temp->l;
			}
			else {
				root = nullptr;
			}
		}
		else {
			while (true) {
				if (temp->val > t) {
					if (temp->l->val == t) {
						c=temp->l->l;
						temp->l = temp->l->r;
						while (temp->l != nullptr) {
							temp = temp->l;
						}
						temp->l = c;
						return;
					}
					temp = temp->l;
				}
				else {
					if (temp->r->val == t) {
						c = temp->r->l;
						temp->r = temp->r->r;
						while (temp->r != nullptr) {
							temp = temp->r;
						}
						temp->r = c;
						return;
					}
					temp = temp->r;
				}
			}
		}
	}
	void zxbl(Node<T> *x) {
		if (x->l != nullptr)zxbl(x->l);
		cout << x->val << " ";
		if (x->r != nullptr)zxbl(x->r);
	}
	void print() {
		if (root == nullptr) {
			cout << "A" << endl;
		}
		else {
			zxbl(root);
		}
	}
};
int main() {
	Tree<int> a;
	int n = 50;
	a.add(50);
	a.add(30);
	a.add(70);
	a.add(15);
	a.add(49);
	a.add(55);
	a.add(80);
	a.cut(49);
	a.add(49);
	a.print();
	getchar();
	return 0;
}


posted @ 2018-03-13 21:41  可爱如我  阅读(315)  评论(0编辑  收藏  举报