Knowledge Guide
HomeDSACompany Practice

medium Same Tree

Problem Statement

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 met following two conditions:

  1. Both tree are structurally identical.
  2. Each corresponding node on both the trees have the same value.

Example 1:

Given the following two binary trees:

Image
Image

Output: true

Explanation: Both trees are structurally identical and have same values.

Example 2:

Given the following two binary trees:

Image
Image

Output: false

Explanation: Trees are structurally different.

Example 3:

Given the following two binary trees:

Image
Image

Output: false

Explanation: Corresponding nodes have different value ( 4 & 9 ).

Constraints:

Try it yourself

Try solving this question here:

✅ Solution Same Tree

Problem Statement

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 met following two conditions:

  1. Both tree are structurally identical.
  2. Each corresponding node on both the trees have the same value.

Example 1:

Given the following two binary trees:

Image
Image

Output: true

Explanation: Both trees are structurally identical and have same values.

Example 2:

Given the following two binary trees:

Image
Image

Output: false

Explanation: Trees are structurally different.

Example 3:

Given the following two binary trees:

Image
Image

Output: false

Explanation: Corresponding nodes have different value ( 4 & 9 ).

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -104 <= Node.val <= 104

Solution

A simple solution would be to recursively check each corresponding node of the two trees. If one of the trees do not have a corresponding node or their values differ, we can conclude that the trees are not the same.

Code

Here is what our algorithm will look like:

java
/** definition for a binary tree node */
// class TreeNode {
//   int val;
//   TreeNode left;
//   TreeNode right;
//   public TreeNode(int val) {
//     this.val = val;
//     this.left = null;
//     this.right = null;
//   }
// }

public class Solution {

  public boolean isSameTree(TreeNode p, TreeNode q) {
    // p and q are both null
    if (p == null && q == null) return true;
    // one of p and q is null
    if (q == null || p == null) return false;
    // one of p and q has different value
    if (p.val != q.val) return false;

    // check left and right subtree recursively
    return isSameTree(p.right, q.right) && isSameTree(p.left, q.left);
  }

  public static void main(String[] args) {
    TreeNode p = new TreeNode(10);
    p.left = new TreeNode(4);
    p.left.left = new TreeNode(1);
    p.right = new TreeNode(15);
    p.right.left = new TreeNode(14);

    TreeNode q = new TreeNode(10);
    q.left = new TreeNode(4);
    q.left.left = new TreeNode(1);
    q.right = new TreeNode(15);
    q.right.left = new TreeNode(14);

    Solution sameTree = new Solution();
    System.out.println(sameTree.isSameTree(p, q));

    q.right.right = new TreeNode(20);
    System.out.println(sameTree.isSameTree(p, q));

    p.right.right = new TreeNode(20);
    System.out.println(sameTree.isSameTree(p, q));

    p.left.val = 9;
    System.out.println(sameTree.isSameTree(p, q));
  }
}

Time Complexity

The solution will take O(min(M, N)) time, where 'M' and 'N' are the number of nodes in the given trees respectively. We are taking minimum of 'M' and 'N', since as soon as we see a difference in value or structure, we do not check the remaining trees.

Space Complexity

We will need O(N) space for the recursion stack in the worst case (when the binary tree is a list). Overall, we will need to store nodes equal to the height of the tree, hence, O(H) space complexity, where H is the height of the given tree.

Making the Algorithm Multi-threaded

To further improve the algorithm, we can make isSameTree() multi-threaded to check the left and right subtrees in separate threads.

We can find how many processors the machine has on which our algorithm is running. We will, then, start multiple threads so that each core can run one thread.

We will use a Volatile Boolean variable isSame so that multiple threads can update its value concurrently.

Here is the code that takes care of this scenario:

java
/** definition for a binary tree node */
// class TreeNode {
//   int val;
//   TreeNode left;
//   TreeNode right;
//   public TreeNode(int val) {
//     this.val = val;
//     this.left = null;
//     this.right = null;
//   }
// }

public class Solution {

  private volatile boolean isSame;

  public boolean isSameTree(TreeNode p, TreeNode q) {
    isSame = true;
    int numThreads = Runtime.getRuntime().availableProcessors();
    return isSameTreeMultiThreaded(p, q, numThreads);
  }

  private boolean isSameTreeMultiThreaded(
    TreeNode p,
    TreeNode q,
    int numThreads
  ) {
    // p and q are both null
    if (p == null && q == null) return true;
    // one of p and q is null
    if (q == null || p == null) return false;
    // one of p and q has different value
    if (p.val != q.val) return false;

    // if we can start more threads, we will spawn a new thread to check the
    // right subtree, otherwise we will do everything in the current thread
    if (numThreads > 0) {
      // spawn a separate thread for checking the right sub-tree
      Thread t1 = new Thread(
        new Runnable() {
          @Override
          public void run() {
            isSame &= isSameTreeMultiThreaded(p.right, q.right, numThreads / 2);
          }
        }
      );
      t1.start();

      // check the left sub-tree in the current thread
      isSame &= isSameTreeMultiThreaded(p.left, q.left, numThreads / 2);

      try {
        t1.join(); // wait for the thread checking the right sub-tree
      } catch (InterruptedException e) {
        System.out.println(e);
      }
    } else { // do everything in the current thread
      isSame &=
        isSameTreeMultiThreaded(p.right, q.right, 0) &&
        isSameTreeMultiThreaded(p.left, q.left, 0);
    }

    return isSame;
  }

  public static void main(String[] args) {
    TreeNode p = new TreeNode(10);
    p.left = new TreeNode(4);
    p.left.left = new TreeNode(1);
    p.right = new TreeNode(15);
    p.right.left = new TreeNode(14);

    TreeNode q = new TreeNode(10);
    q.left = new TreeNode(4);
    q.left.left = new TreeNode(1);
    q.right = new TreeNode(15);
    q.right.left = new TreeNode(14);

    Solution sameTree = new Solution();
    System.out.println(sameTree.isSameTree(p, q));

    q.right.right = new TreeNode(20);
    System.out.println(sameTree.isSameTree(p, q));

    q.right.right = new TreeNode(20);
    p.left.val = 9;
    System.out.println(sameTree.isSameTree(p, q));
  }
}

Time and Space Complexities

Everything has the same complexity as the previous solution.

🤖 Don't fully get this? Learn it with Claude

Stuck on Same Tree? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Same Tree** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Same Tree** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Same Tree**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Same Tree**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes