T
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.
S
- 树的深度如何求?
- 如何判断平衡二叉树?
递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int height(struct TreeNode *root) { // 树的深度
if (root == NULL) {
return 0;
}
else {
int l = height(root->left);
int r = height(root->right);
return (l>r ? l : r) + 1;
}
}
bool isBalanced(struct TreeNode* root) {
if (root == NULL) {
return true;
}
// 判断平衡二叉树
return (isBalanced(root->left) && isBalanced(root->right) && (abs(height(root->left) - height(root->right)) <= 1));
}