Skip to content

Instantly share code, notes, and snippets.

@anupsavvy
Created July 15, 2011 06:35
Show Gist options
  • Save anupsavvy/1084203 to your computer and use it in GitHub Desktop.
Save anupsavvy/1084203 to your computer and use it in GitHub Desktop.
Check to see if the tree is balanced.
package com.example.tree;
import com.example.Node;
// Tree is balanced when the difference between maximum and minimum height is <= 1.
public class Tree{
public static void main(String args[]){
Node root = new Node();
if(checkTreeBalance(root))
System.out.println("Its a balanced tree");
else
System.out.println("Its not a balanced tree");
}
public static boolean checkTreeBalance(Node root){
return (maxHeight(root) - minHeight(root)) <= 1 ;
}
public static int maxHeight(Node root){
if(root == null)
return 0;
return 1 + Math.max(maxHeight(root.getLeft()),maxHeight(root.getRight()));
}
public static int minHeight(Node root){
if(root == null)
return 0;
return 1 + Math.min(minHeight(root.getLeft()),minHeight(root.getRight()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment