标签:二叉排序树 二叉查找树 二叉查找树最小值 二叉排序树最小值 二叉查找树最大值
Node * minValueNode(Node* node) { Node* current = node; //查找最左侧的叶子 while (current->left != NULL) current = current->left; return current; }时间复杂度: 最坏情况下为O(n)
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; }输出:
标签:二叉排序树 二叉查找树 二叉查找树最小值 二叉排序树最小值 二叉查找树最大值
原文地址:http://blog.csdn.net/shltsh/article/details/46510261