思路:根据定义判断 dis=(left-right)《=1是否成立;
方法1:求出每个节点的高度;然后再判断,递归判断左右子树是否是平衡二叉树(重复遍历了节点)
方法2:把求根节点的高度的时候 记录下求得的每一个结点的高度;然后判断左右子树是不是平衡的二叉树;再判断root是不是
代码:
class Solution {
public:
//method1
/*int depth(TreeNode *root)
{
if(!root)return 0;
return 1+max(depth(root->left),depth(root->right));
}
bool IsBalanced_Solution(TreeNode* root)
{
if(!root)return true;
int left=depth(root->left);
int right=depth(root->right);
int dis=abs(left-right);
if(dis<=1)
return IsBalanced_Solution(root->left)&&IsBalanced_Solution(root->right);
return false;
}
*/
/*
int depth(TreeNode *root,bool &res)
{
if(!root)return 0;
//int left=0;
//int right=0;
int left=depth(root->left,res);
int right=depth(root->right,res);
int dis=left-right;
if(dis>1||dis<-1)
res=false;
return 1+max(left,right);
}
bool IsBalanced_Solution(TreeNode* root)
{
if(!root)return true;
bool res=true;
depth(root,res);
return res;
}
*/
bool helper(TreeNode *root,int &dep)
{
if(!root)return true;
int left=0;
int right=0;
if(helper(root->left,left)&&helper(root->right,right))
{
int dis=left-right;
dep=1+max(left,right);
if(dis<-1||dis>1)
return false;
return true;
}
return false;
}
bool IsBalanced_Solution(TreeNode* root)
{
if(!root)return true;
int dep=0;
return helper(root,dep);
}
};