Description:
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 <iostream>
#include <stack>
#define Elementype int
using namespace std;
typedef struct TreeNode //树结点
{
Elementype val;
TreeNode *left;
TreeNode *right;
TreeNode(Elementype x) : val(x), left(nullptr), right(nullptr) {}
} *Tree;
//全局索引变量
int index = 0;
//使用先序遍历创建创建二叉树
void MakeBinaryTree(Tree &T, Elementype value[])
{
Elementype c = value[index++];
if (c == '#')
T = nullptr;
else
{
T = new TreeNode(c);
MakeBinaryTree(T->left, value);
MakeBinaryTree(T->right, value);
}
}
bool isSameTree(Tree T1, Tree T2)
{
stack<Tree> sk;
Tree p = nullptr;
Tree q = nullptr;
sk.push(T1);
sk.push(T2);
while (!sk.empty())
{
p = sk.top();
sk.pop();
q = sk.top();
sk.pop();
if (!p && !q)
continue;
if (!p || !q)
return false;
if (p->val != q->val)
return false;
sk.push(p->left);
sk.push(q->left);
sk.push(p->right);
sk.push(q->right);
}
return true;
}
int main()
{
Tree T1 = nullptr, T2 = nullptr,T3 = nullptr;
//注意,每个结点都要有值,注意这里的取值不要等于35,即#
Elementype data1[11] = { 3, 9, '#', '#', 20, 15, '#', '#', 7, '#', '#' };
Elementype data2[11] = { 3, 9, '#', '#', 20, 15, '#', '#', 7, '#', '#' };
Elementype data3[11] = { 3, 8, '#', '#', 20, 15, '#', '#', 7, '#', '#' };
MakeBinaryTree(T1, data1);
index = 0;
MakeBinaryTree(T2, data2);
index = 0;
MakeBinaryTree(T3, data3);
cout <<"T1 == T2 ? "<<boolalpha<<isSameTree(T1,T2) << endl;
cout << "T1 == T3 ? " << boolalpha << isSameTree(T1, T3) << endl;
system("pause");
return 0;
}
测试: