题注
不能再刷了,再刷天亮了… 今天最后一道,今天还要看看论文呢,毕竟Paper才是王道啊!
题目
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.
分析
这道题本身其实真的挺简单的:分别先判断节点是否全为空或者全为非空且value相同。如果是,则递归判断左右节点是否相同,如果都满足则返回true,否则返回false。
但是这道题我前面提交了好几次都是错的,原因是我多想了一个事情:两个树左左节点和右右节点相同则树相同,那么两个树左右节点和右左节点相同,这两个树是否相同呢?我认为是相同的,但是LeetCode认为是不同的。仔细观察题目,题目中说的是they are structurally identical,因此这种对称树非相同的要求便可以理解了。
错误代码如下:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
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 false;
}
boolean isSameLLTree = isSameTree(p.left, q.left);
boolean isSameRRTree = isSameTree(p.right, q.right);
if (isSameLLTree && isSameRRTree){
return true;
}
boolean isSameLRTree = isSameTree(p.left, q.right);
boolean isSameRLTree = isSameTree(p.right, q.left);
if (isSameLRTree && isSameRLTree){
return true;
}
return false;
}
}
此代码LeetCode会在第49个test返回错误。如果我们将最后的一个判断删除,那么代码就可以Accepted了。
代码
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
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 false;
}
boolean isSameLLTree = isSameTree(p.left, q.left);
boolean isSameRRTree = isSameTree(p.right, q.right);
if (isSameLLTree && isSameRRTree){
return true;
}else{
return false;
}
}
}