#include<iostream>
using namespace std;
struct BstNode
{
int data;
BstNode* left;
BstNode* right;
};
BstNode* GetNewNode(int data)
{
BstNode* newNode = new BstNode;
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
BstNode* Insert(BstNode* root, int data)
{
if(root == NULL)//数是空的
{
root = GetNewNode(data);
return root;
}
else if(data <= root->data)
root->left = Insert(root->left,data);
else root->right = Insert(root->right,data);
return root;
}
bool Search(BstNode* root,int data)
{
if(root == NULL) return false;
if(root->data == data) return true;
else if(data <= root->data) return Search(root->left,data);
else return Search(root->right,data);
}
int FindMin(BstNode* root)//递归方法
{
if(root == NULL)
{
cout << "Error: Tree is empty\n";
return -1;
}
else if(root->left == NULL)
return root->data;
//继续在左子数查找
return FindMin(root->left);
}
int FindMax(BstNode* root)//迭代方法
{
if(root == NULL)
{
cout << "Error: Tree is empty\n";
return -1;
}
BstNode* temp = root;
while(temp->right != NULL)
{
temp = temp->right;
}
return temp->data;
}
int main()
{
BstNode* root = NULL;//表示树是空的
root = Insert(root,15);
root = Insert(root,10);
root = Insert(root,20);
root = Insert(root,25);
root = Insert(root,8);
root = Insert(root,12);
printf("The max number is %d \n",FindMax(root));
printf("The max number is %d \n",FindMin(root));
return 0;
}