点击查看代码
#include<iostream>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode(int x)
{
Node* temp = new Node;
temp->data = x;
temp->left = temp->right = NULL;
return temp;
}
void insert(Node*& travptr, int data) {//Node*& travptr 表示 travptr 是一个引用,引用的是一个指向 Node 类型的指针
if (travptr == NULL)
{
travptr = newNode(data);
return;
}
(data > travptr->data) ? insert(travptr->right, data) : insert(travptr->left, data);
}
int findmin(Node* run) {
if (run == NULL) {
cout << "empty\n";
return -1;//必须返回值
}
if (run->left == NULL) return run->data;//中止情况
else return findmin(run->left);
}//时间复杂度:O(logn)in best case(balanced bst)
int findmax(Node* run) {
if (run == NULL) {
cout << "empty\n";
return -1;//必须返回值
}
if (run->right== NULL) return run->data;//中止情况
else return findmax(run->right);
}//时间复杂度:O(logn)in best case(balanced bst)
int main()
{
Node* root = NULL;
insert(root, 1);
insert(root, 2);
insert(root, 3);
insert(root, 4);
insert(root, 5);
cout << findmin(root) << endl;;
cout << findmax(root) << endl;;
return 0;
}