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.
給定兩個二叉樹哼丈,寫一個函數(shù)檢查它們是否相同脖镀。
如果兩個二叉樹相同結(jié)點的值相同辆它,則認(rèn)為這兩個二叉樹相同晌坤。
My Solution
(Java) Version 1 Time: 0ms:
并沒有什么大坑坝咐,只是簡單地遍歷兩個二叉樹并判斷結(jié)點的值是否相等就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沒有對比應(yīng)該是測試樣例并不大簇搅,簡介得多了
/**
* 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):
一到這些沒有時間區(qū)別的題目的時候完域,就開始比誰的行數(shù)最少了,然后就什么牛鬼蛇神都出現(xiàn)了(哭笑不得.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);
}
}