问题:给出一棵二叉树,判断它是不是二叉树。
一个比较容易想到的做法是,采用动态规则的方法依次求出每一个节点的左子树深度和右子树深度,两者相减,绝对值大于 1 则不是平衡树。为了避免重复计算节点的深度,应该用后序遍历的方法,即先计算子节点的深度,再计算当前节点的深度,这样不会出现重复计算。
代码如下:
struct Tree
{
Tree *left,*right;
int value;
};
static const int MAX_BALANCE_DIFF = 1;
static const int INT_SIZE = 8 * sizeof(int);//当前计算机中一个 int 占几个字节
int fastAbs(int n)
{
return (n ^ (n >> (INT_SIZE - 1))) - (n >> (INT_SIZE - 1));// 见http://blog.youkuaiyun.com/lizhihaoweiwei/article/details/37757901
}
int max(int a,int b)
{
return a >= b ? a : b;
}
int treeDepth(const Tree *theTree,bool * const isBalance)
{
if(!*isBalance)
{
return 0;
}
if(NULL == theTree)
{
return 0;
}
Tree *left = theTree->left;
Tree *right = theTree->right;
int leftDepth = 0,rightDepth = 0;
leftDepth = treeDepth(left,isBalance);
rightDepth= treeDepth(right,isBalance);
if(MAX_BALANCE_DIFF < fastAbs(leftDepth - rightDepth))
{
*isBalance = false;
}
return 1 + max(leftDepth,rightDepth);
}
bool isBanlaceTree(const Tree *theTree)
{
bool isBalance = true;
treeDepth(theTree,&isBalance);
return isBalance;
}