如何判断一棵树是否为镜像?
镜像是指从根节点竖直向下切割,左右镜像对称。
递归:
一棵树是镜像的,那么它的左右子树肯定是镜像的。
左右子树要满足镜像,必须满足:
- 左右子树的值相等。
- 左子树的右子树与右子树的左子树镜像。
- 左子树的左子树与右子树的右子树镜像。
满足以上条件即可,利用递归判断。
typedef int ElementType;
class BinaryTree
{
public:
ElementType Val;
BinaryTree* LeftChild;
BinaryTree* RightChild;
BinaryTree(ElementType val = 0)
{
Val = val;
LeftChild = NULL;
RightChild = NULL;
}
bool isMirror(const BinaryTree* BT)
{
return isMirrorLeftRight(BT->LeftChild, BT->RightChild);
}
bool isMirrorLeftRight(const BinaryTree* LeftChild, const BinaryTree* RightChild)
{
if (LeftChild == NULL && RightChild == NULL)
return true;
else if (LeftChild == NULL || RightChild == NULL)
return false;
else
{
if (LeftChild->Val != RightChild->Val)
return false;
else
return (isMirrorLeftRight(LeftChild->LeftChild, RightChild->RightChild) && isMirrorLeftRight(LeftChild->RightChild, RightChild->LeftChild));
}
}
};
信息来自同实验室应届硕士毕业生。