Last active
August 29, 2015 14:19
-
-
Save HDegano/90f10773fd2c706d72bf to your computer and use it in GitHub Desktop.
Check if a BST 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
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