描述
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.
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 IsSameTwpTree(BinaryTreeNode *proot1, BinaryTreeNode *proot2)
{
if (proot1&&proot2)
{
if (proot1->m_nValue == proot2->m_nValue)
{
return (IsSameTwpTree(proot1->m_pLeft, proot2->m_pLeft) && IsSameTwpTree(proot1->m_pRight, proot2->m_pRight));
}
else
{
return false;
}
}
else if ((!proot1&&proot2) || (proot1&&!proot2))
{
return false;
}
else
{
return true;
}
}
// ====================测试代码====================
// 8
// 6 10
// 5 7 9 11
int main()
{
//===
BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
{
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);
ConnectTreeNodes(pNode8, pNode6, pNode10);
ConnectTreeNodes(pNode6, pNode5, pNode7);
ConnectTreeNodes(pNode10, pNode9, pNode11);
}
//===
BinaryTreeNode* pNode8_1 = CreateBinaryTreeNode(8);
{
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
BinaryTreeNode* pNode11 = CreateBinaryTreeNode(12);
ConnectTreeNodes(pNode8_1, pNode6, pNode10);
ConnectTreeNodes(pNode6, pNode5, pNode7);
ConnectTreeNodes(pNode10, pNode9, pNode11);
}
//===
//PrintTree(pNode8);
//PrintTree(pNode8_1);
//===
bool flag = IsSameTwpTree(pNode8, pNode8_1);
cout << flag << endl;
DestroyTree(pNode8);
DestroyTree(pNode8_1);
}