Hacktoberfest

Home > Data Structures and Algorithms Questions > Given two binary trees, write a function to check if they are the same or not.

Given two binary trees, write a function to check if they are the same or not.


Answer:

Here's a code snippet to check if two binary trees are same or not.

public boolean isSameTree(TreeNode p, TreeNode q) {

  if(p == null && q == null)
     return null;
  if(p!=null && q == null)
     return false;
  if(q!=null && p == null)
     return false;
  if(p.val != q.val)
     return false;
  boolean leftTree = isSameTree(p.left,q.left);
  boolean rightTree = isSameTree(p.right,q.right);
  if(leftTree == true && rightTree == true)
     return true;
  return false;
}