0

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

  • what is *height* of a binary tree? max height? min height? – ogzd Feb 27 '13 at 10:48
  • this is to check if it is height balanced or not. as I am new to coding, I have no idea how to frame this. I need to know the max height of the left sub tree and max height of the right subtree – Jacob Martin Feb 27 '13 at 10:54
  • was looking for that function to find the height using the source above. – Jacob Martin Feb 27 '13 at 11:41

1 Answers1

1

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;
}
Kaerber
  • 1,623
  • 16
  • 21
  • It is implemented right, I have checked testing the code. I am wondering how to call TreeDepth and what parameters to pass. Thank you for the help @Kaerber – Jacob Martin Feb 27 '13 at 12:24
  • You just pass it a tree you want to measure, like that: var depth = TreeDepth( root ); – Kaerber Feb 27 '13 at 16:19