输入一棵二叉树的跟节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左、右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
思路:还记得后序遍历么?
bool IsBalanced(BinaryTreeNode* pRoot,int* pDepth)
{
if(pRoot==nullptr)
{
*pDepth=0;
return true;
}
int left,right;
if(IsBalanced(pRoot->m_pLeft,&left)
&&IsBalanced(pRoot->m_pRight,&right))
{
int diff=left-right;
if(diff<=1&&diff>=-1)
{
*pDepth=1+(left>right?left:right);
return true;
}
}
return false;
}
bool IsBalanced(BinaryTreeNode* pRoot)
{
int depth=0;
return IsBalanced(pRoot,&depth);
}
总结:后序思想体现在if语句中。