IN-FEED-AD

Construct Binary Search Tree from Inorder and Postorder traversal | Construct Binary Search Tree

Construct Binary Search Tree from Inorder and Postorder traversal | Construct Binary Search Tree

firstly we will understand the basics of Inorder, Preorder and Postorder, here i given a example

  • A+B (Inorder)
  • AB+ (Post order)
  • +AB (Preorder)

Binary search tree

Golden Rule:-

  • Preorder---- Root left Right
  • Inorder ---- left Root Right
  • Postorder--- left right Root
Let's take an example to create Binary search tree using given Inorder and Postorder values

Inorder 2-3-4-5-6-8-10
Postorder 2,4,3,6,10,8,5

Step-1:- as we know postorder visits the root node at the end so the last value always represent the root node of the binary search tree.
    therefore 5 is root node, and From above Inorder traversal, we know that a node’s left subtree is traversed before it followed by right subtree. Therefore all the values to the left of 5 in inorder belong to its left subtree and all values to the right belong to its right subtree.
Binary search tree



Step-2:-
now we follow the same rules, as second last element in postorder is 8. So our parent node of right subtree will be 8, and using inorder traversal we find the left and right child of parent node 8.
Binary search tree

Step-3:- Now for left subtree do the same as above. 3 becomes the root. And 2 will be left child and 4 will be right child.
Binary search tree






Ask question #Pywix

Please Like, Comment, Share and Subscribe THANK YOU!



Post a Comment

0 Comments