➜ ~

Playing Hacks and Stuffs!


Project maintained by h4ckyou Hosted on GitHub Pages — Theme by mattgraham

Same Tree

image image

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.

So we’ll be given two binary trees p and q and our goal is to check if they are the same or not

Let’s consider this two binary tress A and B image

From that we can see the best way to know if the nodes have the same value is by traversing and comparing it

So the next thing is how to determine if they are of the same structure

Luckily we can check for that using recursion and for every recursion we check if the nodes of p and q are None, if they are it means they have the same structure, then we can check if the node p happens to be None or vice versa

If that is the case then they are not of the same structure

At the point of each recursion we can check if the key value of p and q are the same

Here’s my solve script: link image

Leetcode Submission Script

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