二叉排序树(搜索、插入、中序遍历==从小到大排序)

#include <iostream>
#include <cstdlib>
using namespace std;
// binary search tree


typedef struct Node {
	int data;
	struct Node * pLeftChild;
	struct Node * pRightChild;
} Node,* PNode;

PNode search(PNode pT, int k) {
	if (pT == NULL) {
		return NULL;
	}

	int value = pT->data;
	if (value == k) {
		cout << "找到" << endl;
		return pT;
	} else if (k < value) {
		return search(pT->pLeftChild, k);
	} else {
		return search(pT->pRightChild, k);
	}
}

bool insert(PNode& pT, int k) {
	if (pT == NULL) {
		pT = (PNode)malloc(sizeof(Node));
		(*pT).data = k;
		(*pT).pLeftChild = (*pT).pRightChild =  NULL;
		return 1;
	} else if (k == pT->data) {
		// 重复
		cout << "重复" << endl;
		return 0;
	} else if (k < pT->data) {
		insert(pT->pLeftChild,k);
	} else if ( k > pT->data) {
		insert(pT->pRightChild,k);
	}
}


void inorder(PNode pT) {
	if (pT == NULL) {
		return ;
	}

	inorder(pT->pLeftChild);
	cout << pT->data << " ";
	inorder(pT->pRightChild);

}

int main() {
	int n;
	cin >> n;

	int t;
	PNode pT = NULL;


	for (int i = 1; i <= n; i++) {
		cin >> t;
		insert(pT,t);
	}
	for (int i = 1; i <= n; i++) {
		cin >> t;
		search(pT,t);
	}
	
	inorder(pT);

}
发布了123 篇原创文章 · 获赞 1 · 访问量 5458

猜你喜欢

转载自blog.csdn.net/bijingrui/article/details/104848793