Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

c++ - Red-Black Tree Height using Recursion

I have these following methods to get the height of a red black tree and this works (I send the root). Now my question is, how is this working? I have drawn a tree and have tried following this step by step for each recursion call but I can't pull it off. I know the general idea of what the code is doing, which is going through all the leaves and comparing them but can anyone give a clear explanation on this?

int RedBlackTree::heightHelper(Node * n) const{
        if ( n == NULL ){
            return -1;
        }
        else{
            return max(heightHelper(n->left), heightHelper(n->right)) + 1;
        }
    }

int RedBlackTree::max(int x, int y) const{
    if (x >= y){
        return x;
    }
    else{
        return y;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, the general algorithm to find the height of any binary tree (whether a BST,AVL tree, Red Black,etc) is as follows

For the current node:
 if(node is NULL) return -1
 else
    h1=Height of your left child//A Recursive call
    h2=Height of your right child//A Recursive call
    Add 1 to max(h1,h2) to account for the current node
    return this value to parent.

An illustration to the above algorithm is as follows:

HeightTree

(Image courtesy Wikipedia.org)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...