Search code examples
c#binary-treebinary-search-treesubtree

How to find the height of the left and right subtree in C#


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


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