判斷一棵樹是否爲平衡二叉樹
思路一:根據求樹的深度的方法,依次得到每個節點左子樹和右子樹的高度,再次計算每個節點其左右高度差是否滿足小於等於1,若都滿足返回真,若不滿足返回假
class Solution {
public:
int GetDepth(TreeNode* proot)
{
if(proot==NULL)
return 0;
int leftDepth=1+GetDepth(proot->left);
int rightDepth=1+GetDepth(proot->right);
return leftDepth>rightDepth?leftDepth:rightDepth;
}
bool IsBalanced_Solution(TreeNode* pRoot)
{
if(pRoot==NULL)
return true;
int left=GetDepth(pRoot->left);
int right=GetDepth(pRoot->right);
if(abs(left-right)>1)
return false;
return (IsBalanced_Solution(pRoot->left)&&
IsBalanced_Solution(pRoot->right));
}
};
思路二:
bool Isbalanced(TreeNode * root,int &Deepth)
{
if (!root)
{
Deepth = 0;
return true;
}
int left_depth, right_depth;
if (Isbalanced(root->left, left_depth) && Isbalanced(root->right, right_depth))
{
int diff = left_depth - right_depth;
if (diff <= 1 && diff >= -1)
{
Deepth = 1 + ((left_depth > right_depth) ? left_depth : right_depth);
return true;
}
}
return false;
}
bool IsBlancedTree(TreeNode* root)
{
int Deepth = 0;
return Isbalanced(root, Deepth);
}