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.
public class Solution {
public boolean Recursive(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 Recursive(p.left, q.left)&&Recursive(p.right, q.right);
}
public boolean Iterative(TreeNode p,TreeNode q){
if( p == null && q == null ) return true;
if( p == null || q == null ) return false;
LinkedList<TreeNode> leftQueue = new LinkedList<TreeNode>();
LinkedList<TreeNode> rightQueue = new LinkedList<TreeNode>();
leftQueue.add(p);
rightQueue.add(q);
while( !leftQueue.isEmpty() && !rightQueue.isEmpty() ){
TreeNode currLeft; TreeNode currRight;
currLeft = leftQueue.remove();
currRight = rightQueue.remove();
if( currLeft == null && currRight == null )
continue;
if( currLeft == null || currRight == null )
return false;
if( currLeft.val != currRight.val )
return false;
leftQueue.add(currLeft.left);leftQueue.add(currLeft.right);
rightQueue.add(currRight.left);rightQueue.add(currRight.right);
}
return true;
}
public boolean isSameTree(TreeNode p, TreeNode q) {
return Iterative(p, q);
// return Recursive(p, q);
}
}