加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

【数据结构】搜索二叉树的相关操作

发布时间:2020-12-15 05:58:53 所属栏目:安全 来源:网络整理
导读:1.查找最小元素 方法1: Position FindM in (B in Tree BST){ if (!BST) return NULL; else if (!BST-left) return BST; else return FindM in (BST-left); } 方法2: int minValue(struct node * node){ struct node * current = node; while (current - le

1.查找最小元素

方法1:

Position FindMin(BinTree BST)
{
    if(!BST) return NULL;
    else if(!BST->left)
        return BST;
    else
        return FindMin(BST->left);  
}

方法2:

int minValue(struct node* node)
{
    struct node* current = node;
    while(current->left!=NULL)
    {
        current  = current->left;
    }
return (current->data);
}

方法1和方法2实质上没有太大区别。

2.查找最大元素

由查找最小元素的算法同理可以得到查找最大元素的算法如下:

方法1:

Position FindMax(BinTree BST)
{
    if(!BST) return NULL;
    else if(!BST->right)
        return BST;
    else
        return FindMin(BST->right); 
}

方法2:

int maxValue(struct node* node)
{
    struct node* current = node;
    while(current->right!=NULL)
    {
        current  = current->right;
    }
return (current->data);
}

3.搜索二叉树插入结点

struct node* insert(struct* node,int data)
{
    if(node==NULL)
        {
            node = (node*)malloc(sizeof(struct node));
            node->data = data;
            node->left = NULL;
            node->right = NULL;
        }
    else 
    {
        if(data<=node->data)
            node->left = insert(node->left,data);
        else
            node->right = insert(node->right,data);
    }
    return node;    
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读