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.
给定两个二叉树,写一个函数检查它们是否相同。
如果两个二叉树相同结点的值相同,则认为这两个二叉树相同。
My Solution
(Java) Version 1 Time: 0ms:
并没有什么大坑,只是简单地遍历两个二叉树并判断结点的值是否相等就ok了,测试样例似乎也没有走极端,用递归也没有超时,确实是Easy题
/**
* Definition for a binary tree node.
* 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;
}
else if((p == null&&q != null)||(p != null&&q == null)){
return false;
}
else if(p.val == q.val){
if(p.left==null&&p.right==null&&q.left==null&&q.right==null){
return true;
}
else if(p.left!=null&&p.right==null&&q.left!=null&&q.right==null){
if(isSameTree(p.left,q.left)){
return true;
}
}
else if(p.left==null&&p.right!=null&&q.left==null&&q.right!=null){
if(isSameTree(p.right,q.right)){
return true;
}
}
else if(p.left!=null&&p.right!=null&&q.left!=null&&q.right!=null){
if(isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)){
return true;
}
}
else{
return false;
}
}
else{
return false;
}
return false;
}
}
(Java) Version 2 Time: 0ms (By saneGuy):
(滑稽.jpg)看了一下别人的写法,果然还是我想太多,都是0ms没有对比应该是测试样例并不大,简介得多了
/**
* Definition for a binary tree node.
* 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;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
(Java) Version 3 Time: 0ms (By dmcoley):
一到这些没有时间区别的题目的时候,就开始比谁的行数最少了,然后就什么牛鬼蛇神都出现了(哭笑不得.jpg)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
return (p == null || q == null) ? p == q : p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}