算法导论(八)二叉查找树

第12章 二叉查找树

#include <iostream>
using namespace std;

struct tnode
{
    int val;
    tnode* left;
    tnode* right;
    tnode* parent;
};
//中序遍历
void inorder_tree_walk(tnode *x)
{
    if (x != NULL)
    {
        inorder_tree_walk(x->left);
        cout << x->val;
        inorder_tree_walk(x->right);
    }
}
//递归
tnode* tree_search(tnode *x, int k)
{
    if (x == NULL || k == x->val)
        return x;
    if (k < x->val)
        return tree_search(x->left, k);
    else
        return tree_search(x->right, k);
}

//非递归
tnode* iterative_tree_search(tnode* x, int k)
{
    while (x != NULL && k != x->val)
    {
        if (k < x->val)
            x = x->left;
        else
            x = x->right;
    }
    return x;
}

tnode* tree_minimum(tnode *x)
{
    while (x->left != NULL)
    {
        x = x->left;
    }
    return x;
}

tnode* tree_maxmum(tnode *x)
{
    while (x->right != NULL)
    {
        x = x->right;
    }
    return x;
}
//后继的概念:大于x->val值的最小的那个结点
tnode* tree_successor(tnode *x)
{
    tnode *y;
    if (x->right != NULL)
    {
        return tree_minimum(x->right);//右不为空,x的后继是大于x->val的最小的那个结点
    }
    y = x->parent;
    while (y != NULL && x == y->right)//直到遇到个是其父结点的左儿子的结点为止.有可能是nil,应该还算好理解
    {
        x = y;
        y = y->parent;
    }
    return y;
}

void tree_insert(tnode *T, tnode *z)
{
    tnode* y = NULL;
    tnode* x = T;
    while (x != NULL)
    {
        y = x;
        if (z->val < x->val)
        {
            x = x->left;
        }
        else
            x = x->right;
    }
    z->parent = y;
    if (y == NULL)//空树
    {
        T = z;
    }
    else if (z->val < y->val)
    {
        y->left = z;
    }
    else
        y->right = z;
}


tnode* tree_delete(tnode *T, tnode *z)
{
    if (z->left == NULL || z->right == NULL)
    {
        y = z;
    }
    else
        y = tree_successor(z);//找到后继

    if (y->left != NULL)//两种情况,结合图12-2和12-4来理解,需要考虑的情况比较多
    {
        x = y->left;
    }
    else
        x = y->right;

    if (x != NULL)//由于这个结点要被去掉,修改其子其父所需要的指向的变化
    {
        x->parent = y->parent;
    }
    if (y->parent == NULL)
    {
        T = x;
    }
    else if (y == y->parent->left)
    {
        y->parent->left = x;
    }
    else
        y->parent->right = x;
    if (y != z)//覆盖原来的要删掉的值
    {
        z->val = y->val;
    }
    return y;
}

int main(void)
{
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值