题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路;
首先确认平衡二叉树定义,首先是二叉树,其次是每个节点的左右子树的高度差的绝对值要小于等于一,并且该节点的左右子树也得是平衡二叉树。
代码:
class Solution {
public://还得是二叉搜索树和平衡的
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot) return true;
int left=getdepth(pRoot->left);
int right=getdepth(pRoot->right);
if(abs(left-right)>1)
return false;
else
return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
private:
int getdepth(TreeNode* pnode)
{
if(!pnode)
return 0;
return 1+max(getdepth(pnode->left), getdepth(pnode->right));
}