華爲2020屆軟件開發二面代碼題

如何判斷一棵樹是否爲鏡像?

鏡像是指從根節點豎直向下切割,左右鏡像對稱。

在這裏插入圖片描述

遞歸:
一棵樹是鏡像的,那麼它的左右子樹肯定是鏡像的。

左右子樹要滿足鏡像,必須滿足:

  1. 左右子樹的值相等。
  2. 左子樹的右子樹與右子樹的左子樹鏡像。
  3. 左子樹的左子樹與右子樹的右子樹鏡像。

滿足以上條件即可,利用遞歸判斷。

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));
		}
	}
};

信息來自同實驗室應屆碩士畢業生。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章