Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active April 13, 2022 12:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/c7570bca58aba37a6559 to your computer and use it in GitHub Desktop.
Save thmain/c7570bca58aba37a6559 to your computer and use it in GitHub Desktop.
public class BalancedTree {
public static int getHeight(Node root){
if(root==null)return 0;
return (1+ Math.max(getHeight(root.left), getHeight(root.right)));
}
public static boolean isBalancedNaive(Node root){
if(root==null)return true;
int heightdifference = getHeight(root.left)-getHeight(root.right);
if(Math.abs(heightdifference)>1){
return false;
}else{
return isBalancedNaive(root.left) && isBalancedNaive(root.right);
}
}
public static void main(String args[]){
Node root = new Node(5);
root.left = new Node(10);
root.right = new Node(15);
root.left.left = new Node(20);
root.left.right = new Node(25);
root.right.left = new Node(30);
root.right.right = new Node(35);
System.out.println(" Is Tree Balanced : " + (new BalancedTree()).isBalancedNaive(root));
root.right.right.right = new Node (40);
root.right.right.right.right = new Node (45);
System.out.println(" Is Tree Balanced : " + (new BalancedTree()).isBalancedNaive(root));
}
}
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
this.left = null;
this.right =null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment