OneCompiler

Same Tree-Leetcode

1816

LeetCode Problem: Same Tree

Problem Statement: The problem is to define if the given two binary trees are identical or not.

Explanation:

1.Number of nodes:Number of nodes in the binary trees should be same.
2.Number of edges:Number of edges in the binary trees should be same.**
3.Check if the both trees are null:If the both trees are null they are considered same.
4.Check if One Tree is null:If One Tree is null and other tree si not null, they are not same.
5.Compare the node values of both binary trees: If values of two binary trees are not equal, they are not considered same.
6.Recursively check the subtrees:Recursively check the subtrees of binary trees if the values are equal or not

Class Solution{
public boolean isSameTree(TreeNode p, TreeNode q){

//If both trees are null, they are the same
if(p==null&&q==null) return true;

// If one tree is null and the other is not, they are not the same
if(p==null||q==null) return false;

// If the values of the nodes are not equal, they are not the same
if(p.val!=q.val) return false;

// Recursively check the left and right subtrees
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
}