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

目录

1.查找流程

2.代码实现


1.查找流程

查找最小值的操作相对比较简单,只需要从根节点递归的遍历到左子树节点即可。当遍历到节点的左孩子为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;
}

2.代码实现

完整的代码如下。

#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

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值