有关二叉排序树的代码实现

参考文章一

参考文章二


#include<iostream>
#include<math.h>
#include<stdio.h>
#include<string.h>
using namespace std;
struct biTree{
	int data;
	biTree *left;
	biTree *right;
};
//插入数据
biTree* insertEle(biTree *t, int key){
	if (t == NULL){
		t = new biTree();
		t->data = key;
		t->left = NULL;
		t->right = NULL;
		return t;
	}
	if(t->data > key){
		t->left = insertEle(t->left, key);
	}else{
		t->right = insertEle(t->right, key);
	}
	return t;
}
//将二叉树从小到大打印出来
void showMinToMax(biTree *t){
	if(t == NULL) return;
	showMinToMax(t->left);
	cout << t->data << endl;
	showMinToMax(t->right);
}
//findElement
biTree* findEle(biTree *t, int target){
	if(t == NULL){
		return NULL;
	}
	if(t->data == target){
		return (biTree*)t;
	}
	if(t->data < target){
		return findEle(t->right, target);
	}else{
		return findEle(t->left, target);
	}
}
// count all node
int countNode(biTree *t){
   if(t == NULL)
	   return 0;
   return 1 + countNode(t->left) + countNode(t->right);
}
// tree height
int treeHeight(biTree *t){
	if(t == NULL){
		return 0;
	}
	
	int leftH = treeHeight(t->left);
	int rightH = treeHeight(t->right);
	
	return leftH >= rightH ? leftH+1 : rightH+1;
}
int main(){
	biTree *root = NULL, *temp;
    int num[10] = {1, 3, 5, 2, 4};
	//插入数据测试
	for(int i = 0 ;i < 5; i++){
		root = insertEle(root, num[i]);
	}
	//从小到大排列测试
	showMinToMax(root);
	//查找元素测试
	temp = findEle(root, 5);
	if(temp == NULL){
		cout << "do not find" <<endl;
	}else{
		cout << temp->data << endl;
	}
	temp = findEle(root, 7);
	if(temp == NULL){
		cout << "do not find" <<endl;
	}else{
		cout << temp->data << endl;
	}
	cout << countNode(root) << endl;
	cout << treeHeight(root) << endl;
	return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值