0100. Same Tree
Easy | Tree | 20 ms (98.94%), 14.3 MB (59.78%)
Last updated
Was this helpful?
Easy | Tree | 20 ms (98.94%), 14.3 MB (59.78%)
Last updated
Was this helpful?
Source: GitHub:
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.
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.