Same Tree
Easy · Trees
You are given the roots of two binary trees. Determine whether the two trees are exactly identical, meaning every node lines up in the same position with the same value. Return true if they match this way, and false otherwise.
Examples
Input: p = [1,2,3], q = [1,2,3]
Output: true
Why: Both trees have identical structure and matching values at every node.
Input: p = [1,2], q = [1,null,2]
Output: false
Why: The single child is on the left in one tree and on the right in the other, so the shapes differ.
Input: p = [1,2,1], q = [1,1,2]
Output: false
Why: The shapes match but the values at the second and third positions are swapped.
Constraints
0 <= number of nodes in each tree <= 100, -10^4 <= node value <= 10^4
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Same Tree. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.