Skip to content

Instantly share code, notes, and snippets.

@rootid
Created June 6, 2015 16:09
Show Gist options
  • Save rootid/6693b870aa50f0dde1cb to your computer and use it in GitHub Desktop.
Save rootid/6693b870aa50f0dde1cb to your computer and use it in GitHub Desktop.
//T(n) = O(n^2)
int maxDepth(TreeNode *root) {
if (root == NULL) {
return 0;
}
int leftDepth = 0;
int rightDepth = 0;
leftDepth = maxDepth(root->left);
rightDepth = maxDepth(root->right);
return 1 + max(leftDepth, rightDepth);
}
public boolean isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
}
return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment