Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created January 12, 2015 07:38
Show Gist options
  • Save dmnugent80/f6bbe4a03aad653c678b to your computer and use it in GitHub Desktop.
Save dmnugent80/f6bbe4a03aad653c678b to your computer and use it in GitHub Desktop.
Is BST balanced- heights of the two sub-trees of any node differs by no more than one
public class TreeNode{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int d){
data = d;
left = null;
right = null;
}
}
public class BinarySearchTree{
TreeNode root;
public BinarySearchTree{
root = null;
}
public boolean getIsBalanced(){
if (root == null){
return false;
}
else if (root.left == null && root.right == null){
return true;
}
else{
return getIsBalancedHelper(root);
}
}
private boolean getIsBalancedHelper(TreeNode node){
if (!node.left && !node.right){
return true
}
else if (node.left != null && node.right == null){
return (node.left.left == null ? true : false);
}
else if (node.left == null && node.right != null){
return (node.right.right == null ? true : false)
}
else{
boolean left = getIsBalancedHelper(node.left);
boolean right = getIsBalancedHelper(node.right);
return (left && right);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment