Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null){
return true;
}
if(p==null || q==null){
return false;
}
Queue<TreeNode> q1=new LinkedList<>();
Queue<TreeNode> q2=new LinkedList<>();
List<Integer> l1=new ArrayList<>();
List<Integer> l2=new ArrayList<>();
q1.add(p);
q2.add(q);
int count=0;
int count1=0;
while(q1.size()!=0 && q2.size()!=0){
TreeNode temp=q1.peek();
TreeNode temp1=q2.peek();
if(temp.val!=temp1.val) return false;
if(temp.left!=null) q1.add(temp.left);
if(temp1.left!=null) q2.add(temp1.left);
if(q1.size()!=q2.size()) return false;
if(temp.right!=null) q1.add(temp.right);
if(temp1.right!=null) q2.add(temp1.right);
if(q1.size()!=q2.size()) return false;
q1.remove();
q2.remove();
}
return true;
}
}