题目:
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,则说明不是高度平衡二叉树;差值小于等于1,则递归分别对左右子树求深度差,对左子树的深度差结果和右子树的的深度差结果进行与运算。
注意!不能按照求深度部分的代码中的注释部分返回,否则会显示超时!
所以递归函数尽量少使用,多次需要用到递归值时,尽量先把递归返回值存入临时变量,而不是每用到一次就计算一次!
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int geth(TreeNode* root){ //求深度的子函数
if(root==NULL)
return 0;
else{
int l = geth(root->left);
int r = geth(root->right);
return 1+(l>r?l:r);
}
// return geth(root->left)>geth(root->right)?geth(root->left)+1:geth(root->right)+1; //不能每用到一次递归就重新计算一次,会超时!
}
bool isBalanced(TreeNode* root) {
if (root==NULL)
return true;
else{
//printf("root->left= %d\nroot->right= %d\nl-r= %d\n",geth(root->left),geth(root->right),abs(geth(root->left)-geth(root->right)));
if((abs(geth(root->left)-geth(root->right))>1)){
printf("false!\n");
return false;
}
else
return isBalanced(root->left)&&isBalanced(root->right);
}
}
};