[leetcode] 110. Balanced Binary Tree (easy)
原题链接
水题
深度搜索每一节点的左右深度,左右深度差大于1就返回false。
class Solution {
public:
bool isBalanced(TreeNode *root) {
bool flag = true;
if (!root) return true;
dfs(root, flag);
return flag;
}
private:
int dfs(TreeNode *root, bool &flag) {
if (!root) return 0;
int leftH = dfs(root->left, flag) + 1;
int rightH = dfs(root->right, flag) + 1;
if (abs(leftH - rightH) > 1) flag = false;
return max(leftH, rightH);
}
};