题目:
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 == NULL && q == NULL)return true;
else if(p == NULL || q == NULL)return false;
if(p->val != q->val)return false;
else if(isSameTree(p->left,q->left) &&isSameTree(p->right,q->right))return true;
else return false;
}
};