题目:
有如下数据结构:
typedef struct TreeNode{ char c; TreeNode *leftChild; TreeNode *rightChild; };
现在实现函数:int CompTree(TreeNode *tree1, TreeNode *tree2);
比较两棵树是否相等
代码:
typedef struct TreeNode{ char c; TreeNode *leftChild; TreeNode *rightChild; }; //两棵树相等的话返回1,否则返回0 int CompTree(TreeNode *tree1, TreeNode * tree2) { bool isTree1NULL = (tree1 == NULL); bool isTree2NULL = (tree2 == NULL); //如果两个树都是空的话 if (isTree1NULL && isTree2NULL) return 1; //如果一棵树是空,而另外一棵树非空的话 if (isTree1NULL != isTree2NULL) return 0; //如果两棵树都是非空的话 if (tree1 ->c != tree2 ->c) return 0; return (CompTree(tree1->left, tree2->left) & CompTree(tree1->right, tree2->right)) | (CompTree(tree1->left, tree2->right) & CompTree(tree1->right, tree2->left)); }
时间: 2024-10-19 05:06:09