数据结构(1) 二叉搜索树

二叉搜索树可以用来排序:
1.每次插入一个数,(按小左大右的规则);
2.中序遍历.
实现代码如下:

#include<cstdio>
struct Node {
	int data;
	Node* p, * lchild, * rchild;
};
class BST {
private:
	Node* root;
	void _delete(Node* &p) {
		if (p==NULL)return;
		_delete(p->lchild);
		_delete(p->rchild);
		if ((p->lchild==NULL)&&(p->rchild==NULL)){delete p; return; }
	}
	void _insert(Node* &p, const int& x) {
		if (p==NULL) {
			p = new Node;
			p->data = x, p->lchild = 0, p->rchild = 0, p->p = 0;
			return;
		}
		if (x<=p->data) {
			_insert(p->lchild, x);
			p->lchild->p = p;
		}
		else {
			_insert(p->rchild, x);
			p->rchild->p = p;
		}
	}
	void _Inorder_print(Node* &p) {
		if (p==NULL)return;
		_Inorder_print(p->lchild);
		printf("%d ", p->data);
		_Inorder_print(p->rchild);
	}
public:
	BST() :root(0){}
	~BST() {_delete(root); }
	void insert(const int& x) { _insert(root, x); }
	void in(int n) {
		while (n--) {
			int x;
			scanf("%d", &x);
			insert(x);
		}
	}
	void Inorder_print() {
		_Inorder_print(root);
	}
};
int main() {
	BST T;
	int n;
	scanf("%d", &n);
	T.in(n);
	T.Inorder_print();
}
posted @ 2021-02-04 13:55  _dwt  阅读(16)  评论(0)    收藏  举报