# Java Solution Recursion for Same Tree Problem

• class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null)
/If both trees do not have left and right subtree,then
it will return Same tree so true should be returned
{
return true;
}
else if(p==null || q==null)
/
if one of the trees does not have left and right
subtree but other have left and right subtree .In that case,Tree is not same,so // false is returned.*/
{
return false;
}

``````if(p.val==q.val) /* Now we are checking both trees values are equal for root of both trees */
{
``````

/* Since now both trees have same values,now we recurse for checking all conditions for the left and right part of the tree otherwise it should not be tree.So false should be returned. */
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);

``````}
else{
return false;
}

}
``````

}

• class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null)
/If both trees do not have left and right subtree,then
it will return Same tree so true should be returned. /
{
return true;
}
else if(p==null || q==null)
/
if one of the trees does not have left and right
subtree but other have left and right subtree .In that case,Tree is not same,so // false is returned.
/
{
return false;
}

``````if(p.val==q.val) /* Now we are checking both trees values are equal for root of both trees */
{
``````

/* Since now both trees have same values,now we recurse for checking all conditions for the left and right part of the tree otherwise it should not be tree.So false should be returned. */
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);

``````}
else{
return false;
}

}
``````

}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.