How to determine if a binary tree is height | C # program to determine if binary tree is height balanced or not ; A binary tree node has data , pointer to left child , and a pointer to right child ; Returns true if binary tree with root as root is height - balanced ; for height of left subtree ; for height of right subtree ; If tree is empty then return true ; Get the height of left and right sub trees ; If we reach here then tree is not height - balanced ; The function Compute the " height " of a tree . Height is the number of nodes along the longest path from the root node down to the farthest leaf node . ; base case tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Driver code
using System ; public class Node { public int data ; public Node left , right ; public Node ( int d ) { data = d ; left = right = null ; } } public class BinaryTree { public Node root ; public virtual bool isBalanced ( Node node ) { int lh ; int rh ; if ( node == null ) { return true ; } lh = height ( node . left ) ; rh = height ( node . right ) ; if ( Math . Abs ( lh - rh ) <= 1 && isBalanced ( node . left ) && isBalanced ( node . right ) ) { return true ; } return false ; } public virtual int height ( Node node ) { if ( node == null ) { return 0 ; } return 1 + Math . Max ( height ( node . left ) , height ( node . right ) ) ; } public static void Main ( string [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; tree . root . left . left . left = new Node ( 8 ) ; if ( tree . isBalanced ( tree . root ) ) { Console . WriteLine ( " Tree ▁ is ▁ balanced " ) ; } else { Console . WriteLine ( " Tree ▁ is ▁ not ▁ balanced " ) ; } } }