结构体:
typedef char BTDataType;
typedef struct BTNode
{
struct BTNode* pLeft;
struct BTNode* pRight;
BTDataType data;
}BTNode;
求二叉树的镜像:
// 求二叉树的镜像
bool Mirror(BTNode* pRoot1,BTNode* pRoot2)
{
if (pRoot1==NULL&&pRoot2==NULL)
{
return 1;
}
if (pRoot1==NULL||pRoot2==NULL)
{
return 0;
}
return pRoot1->data == pRoot2->data
&& Mirror(pRoot1->pLeft, pRoot2->pRight)
&& Mirror(pRoot1->pRight, pRoot2->pLeft);
}
判断是不是子树:
//判断是不是子树
bool isSameTree(struct BTNode *p, struct BTNode *q) {
if (p == NULL && q == NULL) {
return true;
}
if (p == NULL || q == NULL) {
return false;
}
return p->data == q->data
&& isSameTree(p->pLeft, q->pLeft)
&& isSameTree(p->pRight, q->pRight);
}
检测二叉树是否平衡:
//检测二叉树是否平衡
bool IsBalanceTree(BTNode* pRoot, int & depth)
{
//如果为空,往父节点返
if (pRoot == NULL)
{
depth = 0;
return true;
}
//记录左节点和右节点深度
int left = 0;
int right = 0;
//采取传引用的方式,下层递归进行对深度修改以后会影响上一层
if (IsBalanceTree(pRoot->pLeft, left) && IsBalanceTree(pRoot->pRight, right))
{
//计算平衡因子
int pf = right - left;
//判断平衡因子是否合法
if (pfIsInvaild(pf))
{
//合法就让自身加上子树的深度,然后因为是传引用,
//所以当递归回到上一层的时候,
//上层中的right和left就是左右子树的深度
depth = 1 + (right > left ? right : left);
return true;
}
}
return false;
}
//判断平衡因子是否合法
bool pfIsInvaild(const int& pf)
{
return abs(pf) < 2;
}