在 C++ 中查找二叉搜索树中的最小值节点
假设我们有一个二叉搜索树。我们必须找到二叉搜索树中的最小元素。所以如果 BST 如下 -

最小元素将是 1。
我们知道左子树总是保存较小的元素。因此,如果我们一次又一次地遍历左子树,直到 left 为空,我们就可以找到最小元素。
示例
#include<iostream>
using namespace std;
class node{
public:
node *left;
int val;
node *right;
};
node *bst = NULL;
node *getNode(){
node *newNode;
newNode = new node;
return newNode;
}
void insert(node **root, int key){
node *newNode;
newNode = getNode();
newNode->val = key; newNode->left = NULL; newNode->right = NULL;
if(*root == NULL){
*root = newNode;
return;
} else {
if(key < (*root)->val)
insert(&((*root)->left), key);
else
insert(&((*root)->right), key);
}
}
int minElement(){
node* current = bst;
while (current->left != NULL) {
current = current->left;
}
return(current->val);
}
main(){
int item[] = {3, 2, 1, 6, 5, 8};
int n = sizeof(item)/sizeof(item[0]);
int i;
for(i = 0; i<8; i++){
insert(&bst, item[i]);
}
cout << "Minimum element is: " << minElement();
}输出
Minimum element is: 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP