Leetcode 110. Balanced Binary Tree (Easy) (cpp)
Tag: Tree, Depth-first Search
Difficulty: Easy
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) return true;
else if (abs(depth(root->left) - depth(root->right)) > 1) return false;
else return isBalanced(root->left) && isBalanced(root->right);
}
int depth(TreeNode* root) {
if (!root) return 0;
else if (!(root -> left) && !(root -> right)) return 1;
int depth_L = depth(root -> left);
int depth_R = depth(root -> right);
return depth_L > depth_R ? depth_L + 1 : depth_R + 1;
}
};