Same Binary Tree

Same Binary Tree – Easy Level Problem

Given the roots of two binary trees, p and q, return true if the trees are identical; otherwise, return false.

Two binary trees are considered identical if they have the same structure and their corresponding nodes contain the same values.

same binary tree problem

Example 1:

Same Binary Tree Problem 1

Example 2:

Same Binary Tree Problem 2

Constraints:

  • 0 <= The number of nodes in both trees <= 100.
  • -100 <= Node.val <= 100

Hints to Solve Same Binary Tree

Recommendation for Time and Space Complexity:

Aim for a solution with a time complexity of O(n) and a space complexity of O(n), where n is the total number of nodes in the tree.

Hints For Solving Same Binary Tree Problem

Hint 1 :

Can you think of a tree traversal algorithm that works using recursion?

Hint 2 :

Depth First Search (DFS) is a good choice for tree traversal. How can we use it to traverse both trees simultaneously?

Hint 3 :

Start by comparing the root nodes of both trees. At each recursive step, check if both nodes are null or have the same value. If one node is null and the other isn’t, or if their values don’t match, return false. If they match, recursively compare their left and right sub trees. If any recursive call returns false, the trees are not identical.

There are mainly 2 approach to solve this problem:

  1. Depth First Search Method (DFS)
  2. Breadth First Search Method (BFS)

1. Depth First Search (DFS) Method

Use recursion or a stack to traverse both trees simultaneously, comparing nodes one by one. Check left and right sub trees at each step, ensuring both structure and values match.

  • Time complexity: O(n)
  • Space complexity: O(h)
    • Best Case (balanced tree): O(log(n))
    • Worst Case (degenerate tree): O(n)

Where,

  1. n is the number of nodes in the tree.
  2. h is the height of the tree.

Code

2.  Breadth First Search (BFS) Method

Use a queue to traverse both trees level by level, comparing corresponding nodes. Ensure both trees have the same structure and values as you process each level.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

3. Breadth First Search Method

The BFS method uses a queue to traverse the tree level by level. Nodes at the same depth are processed together. By counting the levels traversed, you determine the maximum depth of the tree. This approach is efficient for level-order traversal.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

More Articles