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.
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
val=x;
}
}
public class SameTree {
/**
* @param args
*/
public boolean isSameTree(TreeNode p,TreeNode q){
if(p==q){
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
else if (p==null && q==null){
return true;
}
else if (p==null || q==null){
return false;
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Python:
class Solution:
def isSameTree(self, p, q):
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p == q