二叉搜索树之递归

上一篇写的是关于二叉搜索树的递归方法,这次就写一下非递归的方法吧。
首先是插入,递归的插入就非常简单了,先插入根节点,再判断是要插入左子树,还是右子树。
直接上代码吧。

bool Insert_Nor(const K& key, const V& value)
    {
        return _Insert(_pRoot, key, value);
    }

因为要递归遍历,不能每次都往_pRoot根节点上插,所以需要重新写一个函数,将_pRoot作为参数传过去。

bool _Insert(Node* & pRoot, const K& key, const V& value)
    {
        if(pRoot == NULL)
        {
            pRoot = new Node(key, value);
            return true;
        }
        if(pRoot->_key > key)
            _Insert(pRoot->_pLeft, key, value);
        else
            _Insert(pRoot->_pRight, key, value);
        return false;
    }

递归查找:

Node* Find_Nor(const K& key)
    {
        return _Find(_pRoot, key);
    }
Node* _Find(Node* pRoot, const K& key)
    {
        Node* pCur = pRoot;
        if(pRoot)
        {
            if(pRoot->_key > key)
                return _Find(pRoot->_pLeft, key);
            else if(pRoot->_key < key)
                return _Find(pRoot->_pRight, key);
            else
                return pRoot;
        }
        return NULL;
    }

找到了就返回该节点,没找到就返回NULL。
递归删除:
这里写图片描述
这里写图片描述
代码:

bool Remove_Nor(const K& key)
    {
        return _Remove(_pRoot, key);
    }
bool _Remove(Node*& pRoot, const K& key)
    {
        if(pRoot == NULL)
            return false;
        if(pRoot->_key > key)
            return _Remove(pRoot->_pLeft, key);
        else if(pRoot->_key < key)
            return _Remove(pRoot->_pRight, key);
        else
        {
            Node* pDel = pRoot;
            //左孩子为空
            if(pRoot->_pLeft == NULL)
            {
                pRoot = pRoot->_pRight;
                delete pDel;
                pDel = NULL;
                return true;
            }
            //右孩子为空,左孩子不为空
            else if(pRoot->_pRight == NULL)
            {
                pRoot = pRoot->_pRight;
                delete pDel;
                pDel = NULL;
                return true;
            }
            //左右孩子都不为空
            else
            {
                //先找到右子树的最左结点
                Node* MinNodeInRightTree = pRoot->_pRight;
                while(MinNodeInRightTree->_pLeft)
                    MinNodeInRightTree = MinNodeInRightTree->_pLeft;
                //将最左结点与当前节点值交换
                pDel->_key = MinNodeInRightTree->_key;
                pDel->_value = MinNodeInRightTree->_value;
                return _Remove(pRoot->_pRight, MinNodeInRightTree->_key);
            }
        }
        return false;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值