二叉搜索树中插入一个结点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hansionz/article/details/81985624
1.思路

思路:遇到插入结点这种题目,就大致分为两个步骤。

  • 1.找到合适的插入位置
  • 2.修改指针指向,将给定结点插入

那么在一棵二叉搜索树中要怎么找到合适的插入位置呢?其实也很简单,就是根据二叉搜索树的性质,既二叉搜索树的根节点大于二叉树左子树中的所有结点,小于右子树中的所有结点。将给定值按照这个性质和根节点比较,确定左右子树,在左右子树里继续查找插入的位置,当这个位置为空时,它的前面那个结点必然是它的母亲。
这里写图片描述

2.代码实现
  • 递归实现
//创建一个新的二叉搜索树结点
BSTreeNode* BuyBSTreeNode(BSTDataType x)
{
    BSTreeNode* ret = (BSTreeNode*)malloc(sizeof(BSTreeNode));
    if (ret != NULL)
    {
        ret->_data = x;
        ret->_left = NULL;
        ret->_right = NULL;
    }
    else
    {
        perror("use malloc");
    }
    return ret;
}
//插入结点
int BSTreeInsert(BSTreeNode** root, BSTDataType x)
{
    assert(root);

    BSTreeNode* cur = *root;
    BSTreeNode* parent = NULL;//记录要插入位置的母亲
    //当二叉搜索树没有结点时,必须要改变指针的指向,让它指向第一个结点,所有要传地址(二级指针)
    //插入成功返回1
    if (*root == NULL)
    {
        *root = BuyBSTreeNode(x);
        return 1;
    }
    else//二叉搜索树中有结点
    {
        //1.寻找插入位置
        while (cur != NULL)
        {
            if (cur->_data > x)
            {
                parent = cur;
                cur = cur->_left;
            }
            else if (cur->_data < x)
            {
                parent = cur;
                cur = cur->_right;
            }
            else
            {
                //如果二叉搜索树中有和要插入结点一样的数据,则插入失败,返回0
                return 0;
            }
        }
        //parent为插入结点的母亲,比较确定插入位置在左还是右最后插入
        if (parent->_data > x)
        {
            parent->_left = BuyBSTreeNode(x);
            return 1;
        }
        else
        {
            parent->_right = BuyBSTreeNode(x);
            return 1;
        }
    }
}
  • 非递归实现
//插入结点(插入成功返回1,插入失败返回0)
int BSTreeInsertR(BSTreeNode** root, BSTDataType x)
{
    assert(root);
    //树为空,改变指向根节点指针的指向,要用二级指针
    if ((*root) == NULL)
    {
        *root = BuyBSTreeNode(x);
        return 1;
    }
    //树不为空
    //要插入的数小于根节点的数,则在插入位置在左子树
    if ((*root)->_data > x)
    {
        BSTreeInsertR(&(*root)->_left, x);
    }
    //要插入的数大于根节点的数,则在插入位置在右子树
    else if ((*root)->_data < x)
    {
        BSTreeInsertR(&(*root)->_right, x);
    }
    //要插入的数等于根节点的数,说明此数据不能插入,插入失败
    else
    {
        return 0;
    }
}

猜你喜欢

转载自blog.csdn.net/hansionz/article/details/81985624