Given the roots r1 and r2 of two binary trees, determine whether they are identical. Two trees are considered identical if they have the same structure and the same node values.
The idea is to compare the root node's data and recursively verify that their left and right subtrees are identical. Both trees must have the same structure and data at each corresponding node.
Output
true
Time Complexity:O(n), where n is the number of nodes in the larger of the two trees, as each node is visited once. Auxiliary Space: O(h), where h is the height of the trees, due to the recursive call stack.
[Approach - 2] Using Level Order Traversal (BFS)
The idea is to use level order traversal with two queues to compare the structure and data of two trees. By enqueuing nodes from both trees simultaneously, we can compare corresponding nodes at each level. If nodes at any level differ in data or structure, or if one tree has nodes where the other does not, the trees are not identical.
Output
true
Time complexity: O(n), where n is the number of nodes in the larger of the two trees, as each node is visited once. Auxiliary Space: O(w), where w is the maximum width of the trees at any level, due to the space required for the queues.
[Expected Approach] Using Morris Traversal
Traverse both trees simultaneously using Morris traversal, comparing node values and structure without recursion or stacks. Temporary links are used to navigate subtrees efficiently, and all links are removed after traversal.
Steps:
Start at the root of both trees.
If a node has a left child, go to its left subtree and find the rightmost node there; temporarily link it back to the current node.
Move to the left child; if no left child, compare the nodes of both trees.
After left subtree, follow the temporary link back, then go to the right child.
If any node mismatch or missing node is found, return false.
Remove all temporary links.
Continue until all nodes are visited; if all match, return true.
Output
true
Time Complexity: O(n), where n is the number of nodes in the larger of the two trees, as each node is visited once. Auxiliary Space: O(1), modifying tree temporarily by establishing "threads" to traverse nodes without using recursion or a stack.