输入一棵二叉树,判断该二叉树是否是平衡二叉树。
算法:
判刑节点左子树和右子树深度相差的绝对值是否大于1,如果大于1则false。然后递归判断该节点的左子树和右子树是否是平衡二叉树
代码
int TreeDepth(TreeNode* root){
if(root==NULL)
return 0;
int left = TreeDepth(root->left);
int right = TreeDepth(root->right);
return max(left,right)+1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL)
return true;
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
if(abs(left-right)>1)
return false;
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}