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

#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);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值