Question

How to find the subtree height both left and right, I have used this code in the following link C# BST

Any help would be appreciated.

Kind Regards

Était-ce utile?

La solution

Well, if it's a correct implementation of BST, then they should be balanced.

But to test it, here is an easy recursive implementation.

public int TreeDepth( TreeNode<T> tree, int depth = 0 )
{
    int leftDepth = tree.Left != null 
        ? TreeDepth( tree.Left, depth + 1 ) 
        : depth;
    int rightDepth = tree.Right != null 
        ? TreeDepth( tree.Right, depth + 1 ) 
        : depth;
    return leftDepth >= rightDepth 
        ? leftDepth 
        : rightDepth;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top