Created
June 6, 2015 16:14
-
-
Save rootid/6f063fe3fce04c97809c to your computer and use it in GitHub Desktop.
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
//T(n) = O(n) | |
int dfsHeight (TreeNode *root) { | |
if (root == NULL) return 0; | |
int leftHeight = dfsHeight (root -> left); | |
if (leftHeight == -1) return -1; | |
int rightHeight = dfsHeight (root -> right); | |
if (rightHeight == -1) return -1; | |
if (abs(leftHeight - rightHeight) > 1) { | |
return -1; | |
} else { | |
return max (leftHeight, rightHeight) + 1; | |
} | |
} | |
bool isBalanced(TreeNode *root) { | |
return dfsHeight (root) != -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment