判断两个二叉树是否相等,就是当根节点相等时两数的左右子树对应相等或互换后相等,应使用递归来解
#include "stdafx.h" #include <conio.h> #include <iostream> #include <stdio.h> using namespace std; typedef struct TreeNode { char data; TreeNode *leftchild; TreeNode *rightchild; }; bool CmpTree(TreeNode *Tree1,TreeNode *Tree2) { if (NULL == Tree1 && NULL == Tree2) { return true; } else if (NULL != Tree1 && NULL != Tree2) { return IsTreeCoreEqual(Tree1,Tree2); } else { return false; } } bool IsTreeCoreEqual(TreeNode *Tree1,TreeNode *Tree2) { if (Tree1->data == Tree2->data) { if (NULL == Tree1->leftchild && NULL == Tree2->leftchild && NULL == Tree1->rightchild && NULL == Tree2->rightchild) return true; else return(IsTreeCoreEqual(Tree1->leftchild,Tree2->leftchild) && IsTreeCoreEqual(Tree1->rightchild,Tree2->rightchild) || IsTreeCoreEqual(Tree1->leftchild,Tree2->rightchild) && IsTreeCoreEqual(Tree1->rightchild,Tree2->leftchild)); } else { return false; } }原文链接:https://www.f2er.com/datastructure/383034.html