题目:输入一棵二叉树,判断该二叉树是否是平衡二叉树
思路:
平衡二叉树:某节点的左右子树深度差绝对值不超过1,可以先求左右子树的深度,判断这个节点是不是平衡的。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL)
return true;
int left=deep(pRoot->left);
int right=deep(pRoot->right);
int diff=left-right;
if(diff>1||diff<-1)
return false;
return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
private:
int deep(TreeNode* pRoot)
{
if(pRoot==NULL)
return 0;
int left=deep(pRoot->left);
int right=deep(pRoot->right);
return (left>right)?left+1:right+1;
}
};