Leetcode在线编程same-tree
题目链接
题目描述
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.
题意
判断题目给定的2个二叉树是否相等
解题思路
先判断是否2个可能不能同时为空或者同时为非空(异或大法)
接着若有一个为空,则肯定两个都是空了
最后就是递归判断左右子树是否都是相等
AC代码
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(!p ^ !q)
return false;
if(!p)
return true;
if(p->val == q->val)
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
else
return false;
}
};