在 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
廣告