15% off all plans & roadmaps Use code
See plansLeetCode 100 · Solution & editorial
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Same Tree is a Tree Traversal Patterns (DFS & BFS) problem, in the Recursive Preorder Traversal subpattern. The pattern covers preorder, inorder, level order traversal, LCA, and serialization
Master preorder traversal for tree construction, inversion, and path problems. Visit root before children.
The reference solution runs in O(n) time and O(h) space.
Same Tree has been reported in interviews at Amazon, Google, Microsoft, Apple.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Same Tree is a Tree Traversal Patterns (DFS & BFS) problem, in the Recursive Preorder Traversal subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.