根据平衡二叉树的定义,如果任意节点的左右子树的深度相差不超过1,那这棵树就是平衡二叉树。
首先编写一个计算二叉树深度的函数,利用递归实现。
int Depth(TreeNode*pRoot)
{
if (pRoot == NULL)
return 0;
else
{
int ld = Depth(pRoot->left);
int rd = Depth(pRoot->right);
return ld > rd ? (ld + 1) : (rd + 1);
}
}
bool IsBalanceTree(TreeNode*pRoot)
{
if (pRoot == NULL)
return false;
int ld = Depth(pRoot->left);
int rd = Depth(pRoot->right);
int dif = ld - rd;
if (dif > 1 || dif < -1)
return false;
return IsBalanceTree(pRoot->left) && IsBalanceTree(pRoot->right);
}
二叉树的镜像其实就是原二叉树所有节点的左右子树互相交换后的结果,所以可以用一个递归来解决问题,依次递归二叉树的所有节点,然后交换这个节点左右子树,直到根节点。
void Mirror(TreeNode *pRoot) {
if (pRoot == NULL || (pRoot->left == NULL) && (pRoot->right == NULL))
return;
TreeNode*temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
if (pRoot->left){
Mirror(pRoot->left);
}
if (pRoot->right){
Mirror(pRoot->right);
}
}