Sunday, February 27, 2011

+ C++ Red Black Tree implementation

RedBlackTree.h
------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <vector>

using namespace std;

/*
    Each child of the Red Black Tree
*/
class Node
{
public:
    char *data; /*data*/
    char color;    /*color*/
    Node *left, *right, *parent; /*lelf, right, parent*/

    /*copy constructor*/
    Node(char *data)
    {
        this->data = new char[strlen(data) + 1];
        strcpy(this->data, data);
        color = NULL;
    }

    /*constructor*/
    Node()
    {
        this->data = new char[1];
        color = NULL;
    }

    /*destructor*/
    ~Node()
    {
        delete (this->data);
        color = NULL;
    }
};

/*
    This is a class of Red Black Tre
*/
class RedBlackTree
{
private:
    Node    *Root;    /*root*/
    Node    *Nil;    /*leaf*/

public:
    /*constructor*/
    RedBlackTree            ();

    /*destructor*/
    ~RedBlackTree            ();

    Node*    tree_successor    ( Node* x );

            /*left rotate*/
    int        leftRotate        ( Node *x );
           
            /*right rotate*/
    int        rightRotate        ( Node *x );

            /*insert key*/
    int        insert_key        ( char *data );

            /*fix up*/
    int        fixup            ( Node *z );

            /*delete key*/
    int        delete_key        ( Node *z );

            /*delete fixup*/
    int        delete_fixup    ( Node *x );

            /*in order traverse*/
    void    inOrderTraverse    ( Node *n );

            /*post order delete*/
    void    postOrderDelete    ( Node *n );
};
RedBlackTree.cpp
------------------------------------------------------------------------------------------
#include "RedBlackTree.h"

/**
 *    tree successor
 *    @param: x is Node type data
 *    @return: return y is a another Node type pointer
 */
Node* RedBlackTree::tree_successor( Node* x )
{
    if ( x->right != Nil )
    {
        x = x->right;
       
        while ( x->left != Nil )
        {
            x = x->left;
        }
       
        return x;
    }
   
    Node* y = x->parent;
   
    while ( y != Nil && x == y->right )
    {
        x = y;
        y = y->parent;
    }
   
    return y;
}

/**
 *    left rotate
 *    @param: x is a node type data
 *    @return: 0 by default
 */
int RedBlackTree::leftRotate( Node *x )
{
    Node *y;
    y = x->right;
    x->right = y->left;
    y->left->parent = x;
    y->parent = x->parent;
   
    if ( x->parent == Nil )
        Root = y;
    else if ( x == x->parent->left )
        x->parent->left = y;
    else
        x->parent->right = y;
    y->left = x;
    x->parent = y;
    return 0;
}

/**
 *    right rotate
 *    @param: x is a Node type pointer
 *    @return: 0 by default
 */
int RedBlackTree::rightRotate( Node *x )
{
    Node *y;
   
    y = x->left;
    x->left = y->right;
    y->right->parent = x;
    y->parent = x->parent;
   
    if ( x->parent == Nil )
        Root = y;
    else if ( x == x->parent->right )
        x->parent->right = y;
    else
        x->parent->left = y;
    y->right = x;
    x->parent = y;
    return 0;
}

/**
 *    insert key
 *    @param: data is a char type pointer
 *    @return: 0 by default
 *    @see: fixup()
 */
int RedBlackTree::insert_key( char *data )
{
    Node *x, *y, *z;
   
    y = Nil;
    x = Root;
   
    while ( x != Nil )
    {
        y = x;       
        if ( strcmp( data, x->data ) < 0 )
            x = x->left;       
        else if ( strcmp( data, x->data ) > 0 )
            x = x->right;
        else
            return -1;
    }
   
    z = new Node(data);
    z->parent = y;
    z->color = 'R';
    z->left = z->right = Nil;
   

    if ( y == Nil )
        Root = z;
    else
    {       
        if ( strcmp( data, y->data ) <= 0 )
            y->left = z;
        else
            y->right = z;
    }
   
    fixup( z );

    x = y = NULL;   
    return 0;
}

/**
 *    fixup the node
 *    @param:        z is a Node type pointer
 *    @return:    0 by default
 *    @see:        leftRotate(Node*)
 *    @see:        rightRotate(Node*)
 */
int RedBlackTree::fixup( Node *z )
{
    Node *y;
   
    while ( z->parent->color == 'R' )
    {
        if ( z->parent == z->parent->parent->left )
        {
            y = z->parent->parent->right;
           
            if ( y->color == 'R' )
            {
                z->parent->color = 'B';
                y->color = 'B';
                z->parent->parent->color = 'R';
                z = z->parent->parent;
            }
            else
            {
                if ( z == z->parent->right )
                {
                    z = z->parent;
                    leftRotate( z );
                }
               
                z->parent->color = 'B';
                z->parent->parent->color = 'R';
                rightRotate( z->parent->parent );
            }
        }
        else
        {
            y = z->parent->parent->left;
           
            if ( y->color == 'R' )
            {
                z->parent->color = 'B';
                y->color = 'B';
                z->parent->parent->color = 'R';
                z = z->parent->parent;
            }
            else
            {
                if ( z == z->parent->left )
                {
                    z = z->parent;
                    rightRotate( z );
                }
                z->parent->color = 'B';
                z->parent->parent->color = 'R';
                leftRotate( z->parent->parent );
            }
        }
    }
   
    Root->color = 'B';
   
    y = NULL;
    return 0;
}

/**
 *    delete key
 *    @param:    z is a Node type param
 *    @see:    tree_successor(Node*)
 *    @see:    delete_fixup(Node*)
 *    @return:0 by default
 */
int RedBlackTree::delete_key( Node *z )
{
    Node *x, *y;
   
    if ( z->left == Nil || z->right == Nil )
    {
        y = z;
    }
    else
    {
        y = this->tree_successor( z );
    }
   
    if ( y->left != Nil )
    {
        x = y->left;
    }
    else
    {
        x = y->right;
    }
   
    x->parent = y->parent;
   
    if ( y->parent == Nil )
    {
        Root = x;
    }
    else
    {
        if ( y == y->parent->left )
        {
            y->parent->left = x;
        }
        else
        {
            y->parent->right = x;
        }
    }
   
    if ( y != z )
    {       
        strcpy( y->data, z->data );
        //z->data = y->data;
    }
   
    if ( y->color == 'B' )
    {
        delete_fixup( x );
    }
   
    return 0;
}

/**
 *    delete fixup
 *    @param: x is a Node type param
 *    @return: 0 by default
 *    @see:    leftRotate(Node*)
 *    @see:    rightRotate(Node*)
 */
int RedBlackTree::delete_fixup( Node *x )
{
    Node *w;
   
    while ( x != Root && x->color == 'B' )
    {
        if ( x == x->parent->left )
        {
            w = x->parent->right;
           
            if ( w->color == 'R' )
            {
                w->color = 'B';
                x->parent->color = 'R';
                leftRotate( x->parent );
                w = x->parent->right;
            }
           
            if ( w->left->color == 'B' && w->right->color == 'B' )
            {
                w->color = 'R';
                x = x->parent;
            }
            else if ( w->right->color == 'B' )
            {
                w->left->color = 'B';
                w->color = 'R';
                rightRotate( w );
                w = x->parent->right;
            }
           
            w->color = x->parent->color;
            x->parent->color = 'B';
            w->right->color = 'B';
            leftRotate( x->parent );
            x = Root;
        }
        else
        {
            w = x->parent->left;
           
            if ( w->color == 'R' )
            {
                w->color = 'B';
                x->parent->color = 'R';
                rightRotate( x->parent );
                w = x->parent->left;
            }
           
            if ( w->right->color == 'B' && w->left->color == 'B' )
            {
                w->color = 'R';
                x = x->parent;
            }
            else if ( w->left->color == 'B' )
            {
                w->right->color = 'B';
                w->color = 'R';
                leftRotate( w );
                w = x->parent->left;
            }
           
            w->color = x->parent->color;
            x->parent->color = 'B';
            w->left->color = 'B';
            rightRotate( x->parent );
            x = Root;
        }
    }
   
    x->color = 'B';
   
    return 0;
}

/**
 *    in order traverse
 *    @param:    n is a Node type param
 *    @desc:    recursive calling
 */
void RedBlackTree::inOrderTraverse( Node *n )
{
    if ( n != Nil )
    {   
        inOrderTraverse( n->left );
        puts( n->data );
        inOrderTraverse( n->right );
    }   
}

/**
 *    post order delete
 *    @param: n is a Node type
 *    @desc:    recursive calling
 */
void RedBlackTree::postOrderDelete( Node *n )
{
    if ( n != Nil )   
    {   
        postOrderDelete( n->left );       
        postOrderDelete( n->right );
        delete( n );
    }
}

/**
 *    Constructor
 *    Nil equal Node
 *    Root equal Nil
 */
RedBlackTree::RedBlackTree()
{
    this->Nil = new Node();
    this->Root = Nil;
}

/**
 * destructor
 * @see: postOrderDelete(Node*)
 */
RedBlackTree::~RedBlackTree()
{
    postOrderDelete( this->Root );
    delete (this->Nil);
}

34 comments:

  1. welll ur code provided much help yet our teacher told us that its against the rules of a tree to move from child node to parent node.

    ReplyDelete
  2. buddy , your delete function has some bugs !
    i juz converted the key to int from char* .... insertion was fine but deletion gave segmentation fault after a few delete ops.

    ReplyDelete
  3. Thanks a lot man, it helped a lot in cracking my errors with tree implementation.... keep the good work going on ..... ^_^

    ReplyDelete
  4. As Shrey pointed out, there are bugs in the code... but it isn't actually in the delete code. The Node class does not initialize the left, right, and parent pointers. Therefore, they contain garbage. This causes the delete code compares the node against nil (n != nil), but since the pointer was not initialized to nil the check will fail which causes the delete code to try to delete garbage which leads to heap corruption.

    You could initialize the left, right, and parent pointers to nil... but that means you have to pass nil into the constructor.

    Or, you could initialize the left, right, and parent pointers to NULL then compare against NULL in the delete function.

    ReplyDelete
    Replies
    1. Hi,
      I tried to follow the above code and indeed got failure after the 2nd node deletion.
      Then, I tried to use Nil in the constructor but it didn't work..
      Maybe there are other ideas to solve this problem?
      Thanks!

      Delete
  5. i have so many error when i convert it with dev c++ v.4.9.9 please help me the error is at node*

    ReplyDelete
  6. How you install or reinstall Office 365 or Office 2016 depends on whether your Office product is part of an Office for home or Office for business plan.
    office setup
    office.com/setup
    www.office.com/setup
    Gmail Customer service

    ReplyDelete
  7. Get started with mcafee products today.We are here to help you to setup your mcafee product step by step.
    mcafee.com/activate

    ReplyDelete
  8. In the event that you require a competent and expert social affair to illuminate your issues, Contact to Norton Setup on Norton.com/setup.
    norton setup
    norton.com/setup

    ReplyDelete
  9. YAHOO SUPPORT - TOLL-FREE NUMBERSUS +1-855-619-5888UK +44-1-800-041-8972AUS +61-1-800-941-031. So, whether you are having a problem accessing your Yahoo Mail account or problem performing any function, you can seek instance assistance for your query or concern through Yahoo Customer Support.
    Yahoo Customer Support

    ReplyDelete
  10. We have to know the methods you can easy way to activate YouTube doing Youtube.com/activate. If you are facing issues with YouTube, like how to connect YouTube on your TV, mobile or other devices contact us. Google has provided us the enjoyment, and by YouTube activate, you watch here latest videos, songs, or web series, etc.

    ReplyDelete
  11. For useful and effective instructions on how to hook up roku, complete the instructions given in the section that follows.

    ReplyDelete
  12. Hello just wanted to give you a quick heads up. The text
    in your article seem to be running off the screen in Opera.
    I’m not sure if this is a formatting issue or something to do with web
    browser compatibility but I thought I’d post to let you know.
    The style and design look great though! Hope you get the issue fixed soon. Cheers
    dune 2 vst product key
    rpg maker vx ace
    little snitch crack
    movavi video converter crack plus activation key

    ReplyDelete
  13. Prime Video is a real time feature. Fundamentally it is just for prime clients. The assistance offers a great many Prime Videos at no charge and Prime Members at no charge. In Amazon Prime Video, clients can undoubtedly lease and purchase films and TV shows. Primevideo.com/mytv - Amazon Prime is a help from Amazon that clients need to pay a month to month add up to utilize. Consequently, he can utilize the Amazon Prime help and exploit the entirety of Prime's highlights.
    Read more…

    ReplyDelete
  14. Thanks for your great post! I like to read, you could be a great writer.
    I will always bookmark your blog and come back later. I want to encourage you to keep writing good articles.
    tuxera ntfs crack
    avg pc tuneup crack
    avast secureline vpn crack
    driver fix license key
    roguekiller crack
    nero platinum crack
    m3 data-recovery crack
    cyberlink powerdirector crack

    ReplyDelete
  15. Appreciate the commitment you make
    to your site and the information you submit.
    It's nice to come across another blog from time to time.
    unwanted reprinted information. Read great!
    I've bookmarked your site and included RSS feeds in my google account.
    gridinsoft anti malware crack
    substance designer crack v

    ReplyDelete
  16. This is really a nice and informative. containing all information and also has a great impact on the new technology. Thanks for sharing it.
    virtual dj pro crack
    fl studio osx download
    Minitool Partition Wizard Version
    Iobit Driver Booster Full Torrent

    ReplyDelete
  17. After reading a few of your blog posts, I have to say that I really enjoy your writing style.
    I've added it to my list of favourite websites and will return soon. Please also have a peek at my website and let me know what you think.
    remote desktop manager enterprise crack
    deep freeze crack
    dr web katana crack

    ReplyDelete
  18. I liked it as much as you do here.
    The sketch is attractive, your writing is elegant.
    I still command you to shake what you want
    gives the following. uncomfortable, no doubt arrives faster
    again, as is almost very common indoors if you advocate this walk.
    microsoft toolkit crack
    driver booster pro crack
    microsoft-office 2013 crack
    microsoft-office 2013 crack

    ReplyDelete
  19. Sincerely, I am overjoyed to have discovered your website; I discovered you by mistake when conducting a Google search.
    for another reason, I'm still here to congratulate you on a well-written piece and
    A lovely site on the whole (and I adore the theme/design as well).
    I don't have time to watch everywhere right now, but I saw and added.
    I've subscribed to your RSS feeds, and if I have time, I'll return to
    Continue reading, and keep up the fantastic job.
    microsoft office 2016 crack
    microsoft office 2016 crack
    eset internet security crack

    ReplyDelete
  20. Hello, Your Site is very nice, and it's very helping us this post is unique and interesting, thank you for sharing this awesome information. and visit our blog site also.. Keep it up
    Wickr Me 5.97.4 Crack
    VidJuice UniTube 3.8.0 Crack

    ReplyDelete
  21. Hello, Your Site is very nice, and it's very helping us this post is unique and interesting, thank you for sharing this awesome information. and visit our blog site also.. Keep it up
    PortraitPro 22.0.2 Crack
    IDM Crack 6.40 Build 9 Patch

    ReplyDelete
  22. I am surprised to see this software Because we download this application free and it is easy to use. There are many features and advantages. We may apply this software on our PC in a very easy way. That's Why I recommended this software to you. Download Here

    ReplyDelete
  23. Please know that I'm thoroughly enjoying your site. You've got a lot of interesting information and anecdotes to share.
    https://crackcut.com/articulate-360-crack/

    ReplyDelete
  24. Thank you so much for all of your efforts! As long as you keep going, you'll receive what you deserve.
    https://keygenhere.com/mindmanager-keygen-crack/

    ReplyDelete
  25. Hi. Great Content! But I'd like to recommend an excellent free software website.
    https://vstoriginal.com/waves-tune-real-time-crack/

    ReplyDelete
  26. This is an excellent article for me. I'm hoping you'll continue to post.
    DiskWarrior

    ReplyDelete
  27. Download Software for PC & Mac
    You make it look very easy with your presentation, but I think this is important to Be something that I think I would never understand
    It seems very complex and extremely broad to me. I look forward to your next post,
    Bolide Movie Creator Crack
    Advance Bulk Mailer Crack
    Apple Motion Crack
    BowPad Portable Crack
    Bplan Data Recovery Crack
    DVDFab Passkey Crack

    ReplyDelete