100. Same Tree¶
To determine whether two binary trees are the same, we compare them node by node, ensuring that both structure and values match exactly and do this recursively for all left and right subtrees. At each pair of nodes, we need to check the following possible cases:
- If both nodes are
None, the trees match at this position. - If both nodes exist, their values must be equal, and their left and right subtrees must also be identical.
- If one node exists and the other does not, the trees differ.
By applying this logic recursively, we ensure that every corresponding node in both trees is checked in the same relative position.
Pseudocode
Runtime Complexity
Time: O(n) Space: O(h)