题目:
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.
题意:
给两个二叉树,要求实现判断这两棵树是否相同。
假如两棵树相同,那么对于树上对应的每一个节点,都应该相同,采用中序遍历的办法,一边判断,一边遍历。
代码如下:
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if ((!p&&q) || (p&&!q)) return false;
if (!q && !p) return true;
if (p->val != q->val) return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right) && p->val == q->val;
}
};