All problemsBack
Same Tree
easyGiven the roots of two binary trees p and q, write a function to check if they are the same.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same values.
Test Cases
Copy an input into themain harness and Run to verifyInput
p = [1,2,3], q = [1,2,3]Expected Output
trueInput
p = [1,2], q = [1,null,2]Expected Output
falseExplanation: The structures differ: one has a left child, the other a right child.
Constraints
- The number of nodes in both trees is in the range [0, 100].
- -10^4 <= Node.val <= 10^4
Hints
Hint 1 — click to reveal
Two trees match when their roots match and both subtrees match — that is the recursion.
Hint 2 — click to reveal
Handle the null cases first: both null is true, exactly one null is false.
Java Compiler
Powered by OneCompiler. Starter code loads automatically — edit and hit Run.