如何判斷一棵樹是否爲鏡像?
鏡像是指從根節點豎直向下切割,左右鏡像對稱。
遞歸:
一棵樹是鏡像的,那麼它的左右子樹肯定是鏡像的。
左右子樹要滿足鏡像,必須滿足:
- 左右子樹的值相等。
- 左子樹的右子樹與右子樹的左子樹鏡像。
- 左子樹的左子樹與右子樹的右子樹鏡像。
滿足以上條件即可,利用遞歸判斷。
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));
}
}
};
信息來自同實驗室應屆碩士畢業生。