Same Tree
Problem Statement
You are given the roots of two binary trees, p and q. Decide whether they are the same: they have the same shape, and every pair of nodes at the same position has the same value.
Return true if they are the same, otherwise false.
Two roots, p and q. Either one may be empty.
true if the two trees are the same, false otherwise.
The shapes match, and every position has the same value.
The values are in the same order, but 2 is a left child in p and a right child in q.
The shapes match, but the values of the two children are swapped.
- β’ The number of nodes in both trees is in the range [0, 100].
- β’ β10^4 β€ Node.val β€ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Write each tree in preorder with # for empty children; the trees are the same when the texts are equal
Recurse on both trees at once; any mismatch at a position returns false
Write p as one long string: visit nodes in preorder, write each value, and write # for every empty child. Do the same for q. The # marks make the shape part of the text, so equal strings mean equal shapes and values.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.