Input : Inorder -> 4 2 5 1 3 Preorder -> 1 2 4 5 3 Postorder -> 4 5 2 3 1 Output : Yes Exaplanation : 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 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 above approach:
Time Complexity : O( n * n ), where n is number of nodes in the tree.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if given Preorder, Inorder and Postorder traversals are of same tree | Set 2
- Tree Traversals (Inorder, Preorder and Postorder)
- Print Postorder traversal from given Inorder and Preorder traversals
- Preorder from Inorder and Postorder traversals
- Construct Full Binary Tree from given preorder and postorder traversals
- Construct Tree from given Inorder and Preorder traversals
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Construct a tree from Inorder and Level order traversals | Set 1
- Construct a tree from Inorder and Level order traversals | Set 2
- Construct a Binary Tree from Postorder and Inorder
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Find parent of given node in a Binary Tree with given postorder traversal
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Construct a Binary Search Tree from given postorder
- Cartesian tree from inorder traversal | Segment Tree
- Data Structures | Tree Traversals | Question 1
- Data Structures | Tree Traversals | Question 2
- Data Structures | Tree Traversals | Question 3
- Data Structures | Tree Traversals | Question 4
- Data Structures | Tree Traversals | Question 5