Two trees are said to be identical if they contain same set of elements but may have different structures.
e.g. 4,3,5 and 5,4,3
How to check whether the two trees are identical?
One approach i can think of is to use hashing. For each element in the first tree, the corresponding count is incremented. For each element in the second tree, the count is decremented. At the end, the the hash is empty, we are sure that trees are identical.
Time complexity: O(N)
Space complexity: O(N)
But, this approach doesn’t make use of whether tree is a BST or a simple BINARY TREE.
Approach 2: Take inorder traversal of both the trees in array. We are with two arrays having sorted data. Do a linear search to check whether arrays are identical are not.
Time complexity: O(N)
Space complexity: O(N)
But, I wanted to know that does there exist any better solution?
Your latter solution seems better than your former, as while the worst-case time for the latter is O(N), the best case (where the first elements in the in-order traversals differ) would be Ω(1), while for the former, best-case time would still be Ω(N) as you have to wait until the end to know for sure.
As an optimization for the latter one, though, couldn’t you just use a pointer to the current element in each tree rather than making copies of all the data? The algorithm for in-order traversal of a tree (with natural ordering, at least) doesn’t require making any copies of the data. That way your space complexity would be O(1).