Same Tree - Depth-First Search Pattern

Same Tree in Java using the Depth-First Search pattern: problem statement, approach, template, complexity, and interview tips.

Same Tree

Problem Statement

Check whether two binary trees are structurally identical with equal node values.

Explore as far as possible along each branch before backtracking, using recursion or a stack.

Use this pattern when you explore trees or graphs, enumerate paths, detect cycles, or compute properties from subtrees.

Approach

  1. Define the base case and what each call returns or records.
  2. Track visited nodes for graphs to avoid infinite loops.
  3. Combine child results (or undo state) before returning.

Pattern Template (Java)

void dfs(Node node, Set<Node> visited) {
    if (node == null || !visited.add(node)) return;
    for (Node next : node.neighbors) {
        dfs(next, visited);
    }
}

Adapt this template to the exact rules of Same Tree: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(V + E) time for graphs, O(n) for trees; recursion depth uses O(h) space.

Interview Tips

  • Mention stack overflow risk on deep inputs and the iterative alternative.
  • Detect cycles in directed graphs with three states: unvisited, visiting, visited.
  • Start with a brute-force idea, state its complexity, then explain how the Depth-First Search pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Course Schedule II | Next: Diameter of Binary Tree

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.