Two Trees
100. Same Tree
100Same Tree
Two binary trees are considered the same if they are structurally identical, and the nodes have the same values in the same positions.
- Time
- O(min(m,n))
m =size ofp,n =size ofq.dfs(a, b)recurses on both children together, so as soon as either side runs out of nodes the mismatch is caught and recursion stops - at mostmin(m,n)node pairs are ever visited.- Space
- O(min(m,n))
- The recursion call stack can only go as deep as the smaller tree allows before a node is missing on one side, so it holds at most
min(m,n)frames.
101. Symmetric Tree
A tree is symmetric if the left subtree is a mirror reflection of the right subtree. This means comparing left.left with right.right and left.right with right.left.
- Time
- O(n)
dfsvisits every node exactly once across the mirrored recursion.- Space
- O(h)
- The recursion call stack grows with tree height
h.
1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree
Given two binary trees original and cloned, and a reference to a target node in the original tree, find the corresponding node in the cloned tree. The cloned tree is a deep copy of the original tree.
- Time
- O(n)
dfsvisits up to allnnodes oforiginalin the worst case, whentargetis the last node reached.- Space
- O(h)
- The recursion call stack grows with the tree's height
h.
872. Leaf-Similar Trees
Two trees are leaf-similar if their leaf values, read left to right, form the same sequence. Generate each tree's leaf sequence with a DFS and compare. The recursive variants use a generator (yield) so leaves stream out in order; the O(1)-space variants compare lazily with zip_longest instead of materializing both lists.
- Time
- O(n)
nis the total number of nodes across both trees - the recursion inrecursionvisits every node ofroot1androot2exactly once.- Space
- O(n)
list(recursion(root1))andlist(recursion(root2))materialize every leaf value before the comparison, up toO(n)leaves combined.- The recursion stack only reaches depth
h(the taller tree's height), which is dominated by the materialized leaf lists.