对于这种有单独操作(求树的高度)又夹杂另一操作(随时判断一棵树的左右子树的高度)的,且这一另一操作贯穿于整棵树始终的。要把这两种操作结合起来。
class Solution {
public:
bool flag=true;
int height(TreeNode* root)
{
if(root==NULL)
{
return 0;
}
int lheight=height(root->left);
int rheight=height(root->right);
if(abs(lheight-rheight)>1) flag=false;
return max(lheight,rheight)+1;
}
bool isBalanced(TreeNode* root) {
if(root==nullptr)
{
return true;
}
height(root);
return flag;
}
};
即求树高操作和判断左右子树操作都在height函数里实现。