p = [1,2,3]
q = [1,2,3]TrueCompare two binary trees. Return True only if corresponding positions contain equal values and the same children. An empty position must be empty in both trees.
p = [1,2,3]
q = [1,2,3]TrueThe values and their positions match.
p = [1,2]
q = [1,null,2]FalseThe child is on different sides, so the shapes differ.
p = [1,2,3] q = [1,2,3] output: True
For equal trees with n nodes each, every corresponding pair is checked once. A mismatch may stop the search early.
Recursive calls use O(h) space, where h is the explored height: O(log n) for a balanced tree and O(n) for a skewed tree.
p = [1,2,3] q = [1,2,3] output: True
Both approaches have the same worst-case bounds. Iterative DFS avoids Python's recursion limit; it is not a constant-space solution.
For equal trees with n nodes each, every corresponding pair is checked once. A mismatch may stop the search early.
The stack holds O(h) pending pairs, including empty children. In the worst case it uses O(n) space.