二叉查找树(3) - 查找值最小的节点

来源:互联网 发布:js 更新url不刷新页面 编辑:程序博客网 时间:2024/06/04 19:35
查找最小值的操作是很简单的,只需要从根节点递归的遍历到左子树节点即可。当遍历到节点的左孩子为NULL时,则这个节点就是树的最小值。


上面的树中, 从根节点20开始,递归遍历左子树,直到为NULL。因为节点4的左子树为NULL,则4就是树的最小值。

代码实现查找最小值:
Node * minValueNode(Node* node){    Node* current = node;    //查找最左侧的叶子    while (current->left != NULL)        current = current->left;    return current;}
时间复杂度: 最坏情况下为O(n)

类似地,可以递归的遍历右子树,直到子树为NULL,这样可以找到最大值。

Node* maxValueNode(Node * node ){        Node *current = node;        //查找最右侧的叶子        while (current->right != NULL)              current = current->right;        return current;}
完整的代码如下:
#include <iostream>struct Node{int key;Node *left;Node *right;};Node * minValueNode(Node* node){Node* current = node;//查找最左侧的叶子while (current->left != NULL)current = current->left;return current;}Node* maxValueNode(Node * node){Node *current = node;//查找最右侧的叶子while (current->right != NULL)current = current->right;return current;}// 创建一个新的BST节点Node *createNewNode(int item){Node *temp = new Node;temp->key = item;temp->left = temp->right = NULL;return temp;}//插入新节点至二叉搜索树中Node* insert(Node * node, int key){//空树if (node == NULL)return createNewNode(key);//递归插入。如果已存在指定值,则不插入if (key < node->key)node->left = insert(node->left, key);else if (key > node->key)node->right = insert(node->right, key);//返回未修改的node指针return node;}// 中序遍历二叉搜索树void inorder(Node *root){if (root != NULL){inorder(root->left);std::cout << " " << root->key << " ";inorder(root->right);}}int main(){/* 构建一颗如下所示的BST     55           /     \ 33      77/  \    /  \       22  44  66   88*/Node *root = NULL;root = insert(root, 55);insert(root, 33);insert(root, 22);insert(root, 44);insert(root, 77);insert(root, 66);insert(root, 88);Node *result = minValueNode(root);std::cout << "\n Minimum value in BST is: " << result->key << std::endl;result = maxValueNode(root);std::cout << "\n Maximum value in BST is: " << result->key << std::endl;return 0;}
输出:
Minimum value in BST is: 22
Maximum value in BST is: 88

更多参考:
http://cslibrary.stanford.edu/110/BinaryTrees.html

0 0
原创粉丝点击