Created
January 12, 2015 07:38
-
-
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
This file contains hidden or 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
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