0100. Same Tree
Easy | Tree | 20 ms (98.94%), 14.3 MB (59.78%)
Source: LeetCode - Same Tree GitHub: Solution / Performance
Given the roots of two binary trees p
and q
, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
We could check two trees are identical by different kinds of traversal. For here, we use pre-order traversal.
Instead of iterating two trees separately, we could traverse two trees simultaneously. However, we should take care of the existence of child nodes while traversing.
If two nodes popped from the stack are both null, skip the current iteration.
If one of the nodes popped from the stack is null, return False.
If both nodes popped from the stack are not null, check their values.
Last, append two nodes' left- and right-nodes onto the stack for the next iteration.
Last updated