题目描述:
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.
思路:
这题较为简单,给定两棵树,若都为null,则返回true。若只有一个为null,返回false。若两个节点的val值相同,则再去递归判断其左子树和右子树是否相等,返回二者的&&结果。若两个节点的val值不同,则返回false。
代码:
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null){
return true;
}
if(p==null||q==null){
return false;
}
if(p.val==q.val){
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
return false;
}
}