1. 程式人生 > >判斷兩顆棵二叉樹是否相等

判斷兩顆棵二叉樹是否相等

int CompTree(TreeNode *tree1, TreeNode *tree2)
{
bool isTree1Null = (tree1 == NULL);
bool isTree2Null = (tree2 == NULL);
//其中一個為NULL,而另一個不為NULL,肯定不相等
if (isTree1Null != isTree2Null)
return 1;
//兩個都為NULL,一定相等
if (isTree1Null && isTree2Null)
return 0;
//兩個都不為NULL,如果c不等,則一定不相等
if (tree1->c != tree2->c)
return 1;
//兩個都不為NULL,且c相等,則看兩棵子樹是否相等或者是否互換相等
return (CompTree(tree1->left, tree2->left)&CompTree(tree1->right, tree2->right))|
(CompTree(tree1->left, tree2->right)&CompTree(tree1->right, tree2->left));
}