Created
July 15, 2011 06:35
-
-
Save anupsavvy/1084203 to your computer and use it in GitHub Desktop.
Check to see if the tree is balanced.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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