Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
class Solution {
public:
bool isBalanced(TreeNode *root) {
if (root == NULL) return true; // 这里题目要求是返回真
isBalancedTree = true;
dfs(root, 0);
return isBalancedTree;
}
int dfs(TreeNode * now, int d) {
int ld = 0, rd = 0;
if (now->left != NULL && isBalancedTree) ld = dfs(now->left, 0); // 寻找左子树的最大深度
if (now->right != NULL && isBalancedTree) rd = dfs(now->right, 0); // 寻找右子树的最大深度
if (abs(ld - rd) > 1) isBalancedTree = false; // 如果深度相差超过一
return max(ld, rd) + 1; // 返回包含当前节点的最大深度,目测这个函数还能求出树的最大深度
}
bool isBalancedTree;
};