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);
}
}