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

查找最小值的操作是很简单的,只需要从根节点递归的遍历到左子树节点即可。当遍历到节点的左孩子为NULL时,则这个节点就是树的最小值。

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

上面的树中, 从根节点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

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/shltsh/article/details/46510261
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞