点击查看代码
#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;//必须返回值
}
while (run->left != NULL) {//关注结束条件即可
run = run->left;
}//类似链表
return run->data;
}//时间复杂度:O(logn)in best case(balanced bst)
int findmax(Node* run) {
if (run == NULL) {
cout << "empty\n";
return -1;//必须返回值
}
while (run->right!= NULL) {//关注结束条件即可
run = run->right;
}
return run->data;
}//时间复杂度: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;
}