Problem Statement in English

You’re given the roots of two binary trees, p and q. Write a function to check if the trees are the same or not.


Approach

All you need to do is to traverse the tree in a any-order fashion and store the values in an array. Then compare the two arrays.

Another option is to traverse both trees simultaneously and check if the values are the same.


Solution in Python


class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        pl = []
        ql = []

        def dfs(node: Optional[TreeNode], arr: List):
            if node:
                dfs(node.left, arr)
                dfs(node.right, arr)
            
            arr.append(None if not node else node.val)
            
        dfs(p, pl)
        dfs(q, ql)

        return pl == ql
  • Simultaneously traversing both trees (same time and space complexity):

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

Complexity

  • Time: $O(n)$
    Since there are $n$ elements in the tree.

  • Space: $O(n)$
    Since there are $n$ elements in the tree.


And we are done.