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

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;    
}
全部评论

相关推荐

头发暂时没有的KFC总裁:找廉价劳动力罢了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务