1.题目:
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
Given a binary tree, determine if it is height-balanced.
2.代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int countFloor(struct TreeNode* root) {
if(root==NULL)
return 0;
return 1+fmax(countFloor(root->left),countFloor(root->right));
}
//对于每个节点
//1.先看自己是不是平衡,方法是看左右子树高度差值
//2.之后分别看自己两个子树是不是平衡
//两项有一个不是就返回false;
bool isBalanced(struct TreeNode* root) {
if(root==NULL)
return true;
if(abs(countFloor(root->left)-countFloor(root->right))>1)
return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
3.知识点:
二叉树递归。