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

来源:互联网 发布:jsp调用javascript 编辑:程序博客网 时间:2024/05/17 06:27

第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;}


原创粉丝点击