Software & Finance





C++ - Binary Search Tree Depth





 

Here is C++ code for calculating the depth of the binary search tree node. All the nodes to left are less than the current node value and all nodes to the right are greater than the current node value. It would be true for each and every node in the binary search tree. Click here for validating binary search tree.

 

typedef struct _BSTNode

{

    struct _BSTNode *left;

    struct _BSTNode *right;

    int data;

} BSTNode;

 

static BSTNode *root = NULL;

 

int MaxDepth(BSTNode *node)

{

    if(node == NULL)

        return 0;

    int ldepth = MaxDepth(node->left);

    int rdepth = MaxDepth(node->right);

 

    int max = (ldepth > rdepth) ? ldepth : rdepth;

 

    return (max + 1);

}