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.
题解:判断是一个二叉树是否平衡,需要满足任意左右子树的高度相差小于1,其实也就是深度优先遍历的问题,计算所有子树高度差,依次判断;
class Solution {
private:
int dfsHeight (TreeNode *root) {
if(root == NULL) return 0;
int leftHeight = dfsHeight (root -> left);
if(leftHeight == -1) return -1;
int rightHeight = dfsHeight (root -> right);
if(rightHeight == -1) return -1;
if(abs(leftHeight - rightHeight) > 1) return -1;
return max(leftHeight, rightHeight) + 1;
}
public:
bool isBalanced(TreeNode *root) {
return dfsHeight(root) != -1;
}
};
结果: