题解:根据平衡二叉树的定义,左右子树的高度差不超过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 heightTree(TreeNode* root){
if(root==NULL){
return 0;
}
else if(root->left==NULL&&root->right==NULL){
return 1;
}
else{
return max(heightTree(root->left),heightTree(root->right))+1;
}
}
bool isBalanced(TreeNode* root) {
if(root==NULL){
return true;
}
if(abs(heightTree(root->left)-heightTree(root->right))>1){
return false;
}
return isBalanced(root->left)&&isBalanced(root->right);
}
};
耗时16ms.