LeetCode #100 Same Tree Solution & Explanation

LeetCode Problem

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

LeetCode#100 Examples
LeetCode#100 Examples and Constraints

Solution

We can write a easy recursion function for this problem.

In each recursion, if

  • both p and q equal to null, then return true
  • one of them equals to null and another isn’t, then return false
  • if them value is not the same, return false

C# Solution

public class Solution {
    public bool IsSameTree(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 IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right);
    }
}

Java Solution

class Solution {
    public boolean isSameTree(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 isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

Python3 Solution

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if(p==None and q==None):
            return True
        
        if(p==None or q==None):
            return False
        
        if(p.val != q.val):
            return False
        
        return self.isSameTree(p.left, q.left) and  self.isSameTree(p.right, q.right)

JavaScript Solution

var isSameTree = function(p, q) {
    if(!p && !q)
    {
        return true;
    }

    if(!p || !q)
    {
        return false;
    }

    if(p.val != q.val)
    {
        return false;
    }

    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};

Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by clicking some ad, Thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link : Same Tree – LeetCode

Random post

Leave a Reply

Your email address will not be published. Required fields are marked *