Photo by Wim van 't Einde on Unsplash

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.

Approach 1: Recursion


The simplest strategy here is to use recursion. Check if p and q nodes are not None, and their values are equal. If all checks are OK, do the same for the child nodes recursively.

Approach 2: Iteration


Start from the root and then at each iteration pop the current node out of the queue. Then do the same checks as in the approach 1 :

  • p and p are not Null
  • p.val is equal to q.val

and if checks are OK, push the child nodes.

Complexity Analysis

  • Time complexity : O(N) since each node is visited exactly once.
  • Space complexity : O(log(N)) in the best case of completely balanced tree and O(N) in the worst case of completely unbalanced tree, to keep a queue.

Full Stack Programmer, love to solve problem’s during free time.