Check if given Preorder, Inorder and Postorder traversals are of same tree
Input : Inorder -> 4 2 5 1 3 Preorder -> 1 2 4 5 3 Postorder -> 4 5 2 3 1 Output : Yes Explanation : All of the above three traversals are of the same tree 1 / \ 2 3 / \ 4 5 Input : Inorder -> 4 2 5 1 3 Preorder -> 1 5 4 2 3 Postorder -> 4 1 2 3 5 Output : No
The most basic approach to solve this problem will be to first construct a tree using two of the three given traversals and then do the third traversal on this constructed tree and compare it with the given traversal. If both of the traversals are same then print Yes otherwise print No. Here, we use Inorder and Preorder traversals to construct the tree. We may also use Inorder and Postorder traversal instead of Preorder traversal for tree construction. You may refer to this post on how to construct a tree from given Inorder and Preorder traversal. After constructing the tree, we will obtain the Postorder traversal of this tree and compare it with the given Postorder traversal.
Below is the implementation of the above approach:
Time Complexity : O( n * n ), where n is number of nodes in the tree.
Space Complexity: O(n), for call stack
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Efficient algorithm using hash map to store indices of inorder elements :
While building the tree from Inorder and Preorder traversal we need to check if the inorder and preorder traversals are valid themself for some tree, and if yes , then keep building the tree, but if valid binary tree can not be built from given inorder and preorder traversal, then we must stop building the tree and return false. And also we can build the tree from inorder and preorder traversal in O(n) time using hashmap to store the indices of the inorder elements’ array.
Time Complexity: O(N)
Auxiliary Space: O(N), where N is number of nodes in the tree.