Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:19
Show Gist options
  • Save HDegano/90f10773fd2c706d72bf to your computer and use it in GitHub Desktop.
Save HDegano/90f10773fd2c706d72bf to your computer and use it in GitHub Desktop.
Check if a BST is balanced
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public bool IsBalanced(TreeNode root) {
if(root == null) return true;
return checkHeight(root) != -1;
}
private int checkHeight(TreeNode root){
if(root == null) return 0;
int lHeight = checkHeight(root.left);
if(lHeight == -1) return -1;
int rHeight = checkHeight(root.right);
if(rHeight == -1) return -1;
if(Math.Abs(rHeight - lHeight) > 1) return -1;
return Math.Max(rHeight, lHeight) + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment