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