AlgoMaster Logo

Same Tree

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Depth-First Search (DFS)

Intuition:

The basic idea is to recursively compare the two trees' nodes. If both trees' nodes have the same value, then we recursively check their left children and their right children. If all corresponding nodes in the two trees are equal, then the trees are the same.

  1. Base Cases:
    • If both nodes we're comparing are null, they are identical at this subtree level.
    • If only one of them is null, they're not identical.
    • If both nodes are not null but have different values, they're not identical.
  2. Recursive Case:
    • Compare the left subtree of both nodes.
    • Compare the right subtree of both nodes.

Code:

2. Iterative Breadth-First Search (BFS)

Intuition:

Instead of doing it recursively, we can use an iterative method to traverse both trees level by level using a queue. At each node, we check if both nodes are null or if one is null. If both nodes are non-null, we compare their values and enqueue their children.

  1. Use a queue to keep track of nodes from both trees.
  2. Start by adding the root nodes of both trees to the queue.
  3. While the queue is not empty, process each pair of nodes:
    • If both nodes are null, continue.
    • If one node is null, the trees are not identical.
    • If values of the nodes are different, the trees are not identical.
    • Otherwise, enqueue left and right children of both nodes.

Code: