Given Preorder, Inorder and Postorder traversals of some tree. The task is to check if they all are of the same tree.
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
We already have discussed an approach to solve the above problem by constructing a tree using any two traversals in the previous article.
In this article, an approach without using any extra space is discussed.
- Search for the first element of preorder array in the inorder array and store it’s index as idx, if it doesn’t exist then return False.
- Everything from 0th index for inorder and postorder and from 1st index for preorder of length idx becomes left subtree for first element of the preorder array.
- Everything from position idx+1 for inorder and preorder and from idx for postorder of length (length-idx-1) becomes right subtree for first element of preorder array.
- Repeat the steps 1 to 3 recursively until length of arrays become either 0 (in which case we
return true) or 1 (in which case we return True only if all three arrays are equal, else False).
Below is the implementation of the above approach:
- Check if given Preorder, Inorder and Postorder traversals are of same tree
- Tree Traversals (Inorder, Preorder and Postorder)
- Preorder from Inorder and Postorder traversals
- Print Postorder traversal from given Inorder and Preorder traversals
- Construct Tree from given Inorder and Preorder traversals
- Construct Full Binary Tree from given preorder and postorder traversals
- Construct a Binary Tree from Postorder and Inorder
- Construct a tree from Inorder and Level order traversals | Set 2
- Construct a tree from Inorder and Level order traversals | Set 1
- Check if an array represents Inorder of Binary Search tree or not
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Cartesian tree from inorder traversal | Segment Tree
- Data Structures | Tree Traversals | Question 6
- Data Structures | Tree Traversals | Question 4
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.