Given the roots of two binary trees p and q, 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.
Input: p = [1,2,3], q = [1,2,3]
Output: true
Input: p = [1,2], q = [1,null,2]
Output: false
public boolean isSameTree(TreeNode p, TreeNode q) {
// recurision method
if (p == null && q == null) return true;
if (p == null && q != null || p != null && q == null) return false;
if (p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
public boolean isSameTree(TreeNode p, TreeNode q) {
// iteration method
if (p == null && q == null) return true;
if (p == null && q != null || p != null && q == null) return false;
Stack<TreeNode> stackP = new Stack<>();
Stack<TreeNode> stackQ = new Stack<>();
stackP.add(p);
stackQ.add(q);
while (!stackP.isEmpty() && !stackQ.isEmpty()) {
TreeNode tmpP = stackP.pop();
TreeNode tmpQ = stackQ.pop();
if (tmpP.val != tmpQ.val) return false;
if (tmpP.left != null && tmpQ.left != null) {
stackP.push(tmpP.left);
stackQ.push(tmpQ.left);
} else if (tmpP.left == null && tmpQ.left == null) {
} else {
return false;
}
if (tmpP.right != null && tmpQ.right != null) {
stackP.push(tmpP.right);
stackQ.push(tmpQ.right);
} else if (tmpP.right == null && tmpQ.right == null) {
} else {
return false;
}
}
if (!stackP.isEmpty() || !stackQ.isEmpty()) return false;
return true;
}
public boolean isSameTree(TreeNode p, TreeNode q) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(p);
queue.add(q);
while(!queue.isEmpty()){
TreeNode f = queue.poll();
TreeNode s = queue.poll();
if(f == null && s == null){
continue;
}else if(f == null || s == null || f.val != s.val){
return false;
}
queue.add(f.left);
queue.add(s.left);
queue.add(f.right);
queue.add(s.right);
}
return true;
}