How to determine if a binary tree is height | 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
class Node { int data ; Node left , right ; Node ( int d ) { data = d ; left = right = null ; } } class BinaryTree { Node root ; boolean 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 ; } 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 ) ) System . out . println ( " Tree ▁ is ▁ balanced " ) ; else System . out . println ( " Tree ▁ is ▁ not ▁ balanced " ) ; } }