bool isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int left = depth(root.left);
int right = depth(root.right);
if (left - right > 1 || left - right < -1)
{
return false;
}
else
{
return isBalanced(root.left) && isBalanced(root.right); // can’t we write else { return false; } and not doing this dfs becauz we are already getting the height of the tree
}
}
}
int depth(TreeNode n) {
if (n == null) {
return 0;
}
if (n.left == null && n.right == null) {
return 1;
}
else {
int left = depth(n.left);
int right = depth(n.right);
return 1 + (left > right ? left : right);
}