1. 程式人生 > >5.1.9—二叉樹的遍歷—Symmetric Tree

5.1.9—二叉樹的遍歷—Symmetric Tree

描述
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same
value.

#include "BinaryTree.h"
#include <stack>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
//===判斷一棵二叉樹是否對稱------遞迴版本
bool IsSymmetricTwoTree(BinaryTreeNode *proot1, BinaryTreeNode *proot2)
{
	if (!proot1&&!proot2) return true;
	else if (!proot1 || !proot2) return false;
	else
	{
		return (proot1->m_nValue == proot2->m_nValue)
			&& IsSymmetricTwoTree(proot1->m_pLeft, proot2->m_pRight)
			&& IsSymmetricTwoTree(proot1->m_pRight, proot2->m_pLeft);
	}
}
bool IsSymmetric1(BinaryTreeNode *proot)
{
	if (!proot) return true;
	else return IsSymmetricTwoTree(proot->m_pLeft, proot->m_pRight);
}
//===判斷一棵二叉樹是否對稱------迭代版本
bool IsSymmetric2(BinaryTreeNode *proot)
{
	if (!proot) return true;

	stack<BinaryTreeNode*> temp;
	temp.push(proot->m_pLeft);
	temp.push(proot->m_pRight);
	while (!temp.empty())
	{
		auto p= temp.top();
		temp.pop();
		auto q = temp.top();
		temp.pop();
		if (!p&&!q) continue;
		if (!p || !q) return false;
		if (p->m_nValue != q->m_nValue) return false;

		temp.push(q->m_pLeft);
		temp.push(p->m_pRight);
		temp.push(q->m_pRight);
		temp.push(p->m_pLeft);
	}
	return true;
}

// ====================測試程式碼====================
//            8
//        6      6
//       9 9    9  9
int main()
{
	//===
	BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
	BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
	BinaryTreeNode* pNode10 = CreateBinaryTreeNode(6);
	BinaryTreeNode* pNode5 = CreateBinaryTreeNode(9);
	BinaryTreeNode* pNode7 = CreateBinaryTreeNode(9);
	BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
	BinaryTreeNode* pNode11 = CreateBinaryTreeNode(5);

	ConnectTreeNodes(pNode8, pNode6, pNode10);
	ConnectTreeNodes(pNode6, pNode5, pNode7);
	ConnectTreeNodes(pNode10, pNode9, pNode11);
	
	//===
	//PrintTree(pNode8);
	//===
	bool flag1 = IsSymmetric1(pNode8);
	cout << flag1 << endl;
	//===
	bool flag2 = IsSymmetric2(pNode8);
	cout << flag2 << endl;

	DestroyTree(pNode8);
}