二叉查找树(3) - 查找值最小的节点
来源:互联网 发布:js 更新url不刷新页面 编辑:程序博客网 时间:2024/06/04 19:35
查找最小值的操作是很简单的,只需要从根节点递归的遍历到左子树节点即可。当遍历到节点的左孩子为NULL时,则这个节点就是树的最小值。
上面的树中, 从根节点20开始,递归遍历左子树,直到为NULL。因为节点4的左子树为NULL,则4就是树的最小值。
代码实现查找最小值:
类似地,可以递归的遍历右子树,直到子树为NULL,这样可以找到最大值。
Minimum value in BST is: 22
Maximum value in BST is: 88
更多参考:
http://cslibrary.stanford.edu/110/BinaryTrees.html
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
- 二叉查找树(3) - 查找值最小的节点
- data_struction_test3:二叉查找树,查找值最小的结点
- 查找二叉树节点
- 查找二叉树删除节点的操作
- 二叉查找树中节点的删除。
- 二叉树公共祖先节点的查找
- 删除二叉查找树的节点-LintCode
- 检测二叉查找树节点的情况
- 删除二叉查找树的节点
- 删除二叉查找树的节点
- 删除二叉查找树的节点
- 二叉查找树中节点的删除
- LintCode:删除二叉查找树的节点
- LintCode : 删除二叉查找树的节点
- 二叉查找树节点的删除
- 删除二叉查找树的节点
- 删除二叉查找树的节点-LintCode
- 删除二叉查找树的节点
- Android自定义View——自定义搜索框(SearchView)
- 正则表达式 (1)
- 2015061505 - 代码分析之代码格式(2)
- Thread.UncaughtException接口
- SGU138 Games of Chess
- 二叉查找树(3) - 查找值最小的节点
- Java基础之数组
- 数据库中如何分类、分组并总计SQL数据
- Python小知识学习(重要)
- Spark入门——6 SparkStreaming
- Android中ContentProvider组件详解
- Linux下的.sh文件在windows下修改后无法执行
- 专访谢宇:拒绝做程序员“砖工”
- c#模拟js escape方法