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.
很简单的一道题,只需要递归遍历树即可。退出条件写详细一点,分为如下几种情况:
两棵树全为nullptr
两棵树中一个为nullptr 一个不为空
两棵树中都不为空
当两棵树都不为空的时候,那么当前树相等,就等价于左子树和右子树全都相等,而且当前根节点的val也相同
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if(p==nullptr && q == nullptr)return true; else if((p!=nullptr && q==nullptr) || (p==nullptr && q!=nullptr))return false; else if(p->val == q->val){ return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); }else{ return false; } } };