Given the roots of two binary trees
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.
Input: p = [1,2,3], q = [1,2,3]
Input: p = [1,2], q = [1,null,2]
Input: p = [1,2,1], q = [1,1,2]
Approach 1: Recursion
The simplest strategy here is to use recursion. Check if
q nodes are not
None, and their values are equal. If all checks are OK, do the same for the child nodes recursively.
Approach 2: Iteration
Start from the root and then at each iteration pop the current node out of the queue. Then do the same checks as in the approach 1 :
p.valis equal to
and if checks are OK, push the child nodes.
- Time complexity : O(N) since each node is visited exactly once.
- Space complexity : O(log(N)) in the best case of completely balanced tree and O(N) in the worst case of completely unbalanced tree, to keep a queue.