Skip to content

Instantly share code, notes, and snippets.

@rootid
Created June 6, 2015 16:14
Show Gist options
  • Save rootid/6f063fe3fce04c97809c to your computer and use it in GitHub Desktop.
Save rootid/6f063fe3fce04c97809c to your computer and use it in GitHub Desktop.
//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