Open In App
Related Articles

Check if given Preorder, Inorder and Postorder traversals are of same tree

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given Preorder, Inorder, and Postorder traversals of some tree. Write a program to check if they all are of the same tree. 

Examples: 

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: 

C++


                    

Java


                    

Python3


                    

C#


                    

Javascript


                    

Output
Yes

Time Complexity : O( n * n ), where n is number of nodes in the tree.
Space Complexity: O(n), for call stack

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.

Implementation:

C++


                    

Java

<div id="highlighter_895094" class="syntaxhighlighter nogutter  "><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="comments">// Java code for the above approach </code></div><div class="line number2 index1 alt1"><code class="keyword">import</code> <code class="plain">java.util.*; </code></div><div class="line number3 index2 alt2"><code class="undefined spaces"> </code> </div><div class="line number4 index3 alt1"><code class="keyword">class</code> <code class="plain">Node { </code></div><div class="line number5 index4 alt2"><code class="undefined spaces">  </code><code class="keyword">int</code> <code class="plain">data; </code></div><div class="line number6 index5 alt1"><code class="undefined spaces">  </code><code class="plain">Node left, right; </code></div><div class="line number7 index6 alt2"><code class="undefined spaces"> </code> </div><div class="line number8 index7 alt1"><code class="undefined spaces">  </code><code class="plain">Node(</code><code class="keyword">int</code> <code class="plain">val) </code></div><div class="line number9 index8 alt2"><code class="undefined spaces">  </code><code class="plain">{ </code></div><div class="line number10 index9 alt1"><code class="undefined spaces">    </code><code class="plain">data = val; </code></div><div class="line number11 index10 alt2"><code class="undefined spaces">    </code><code class="plain">left = right = </code><code class="keyword">null</code><code class="plain">; </code></div><div class="line number12 index11 alt1"><code class="undefined spaces">  </code><code class="plain">} </code></div><div class="line number13 index12 alt2"><code class="plain">} </code></div><div class="line number14 index13 alt1"><code class="undefined spaces"> </code> </div><div class="line number15 index14 alt2"><code class="keyword">class</code> <code class="plain">Main { </code></div><div class="line number16 index15 alt1"><code class="undefined spaces">  </code><code class="keyword">static</code> <code class="plain">Node buildTreeFromInorderPreorder( </code></div><div class="line number17 index16 alt2"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">inStart, </code><code class="keyword">int</code> <code class="plain">inEnd, </code><code class="keyword">int</code><code class="plain">[] preorder, </code></div><div class="line number18 index17 alt1"><code class="undefined spaces">    </code><code class="plain">Map<Integer, Integer> inorderIndexMap, </code></div><div class="line number19 index18 alt2"><code class="undefined spaces">    </code><code class="keyword">boolean</code><code class="plain">[] notPossible, </code><code class="keyword">int</code> <code class="plain">preIndex) </code></div><div class="line number20 index19 alt1"><code class="undefined spaces">  </code><code class="plain">{ </code></div><div class="line number21 index20 alt2"><code class="undefined spaces"> </code> </div><div class="line number22 index21 alt1"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(inStart > inEnd) </code></div><div class="line number23 index22 alt2"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="keyword">null</code><code class="plain">; </code></div><div class="line number24 index23 alt1"><code class="undefined spaces"> </code> </div><div class="line number25 index24 alt2"><code class="undefined spaces">    </code><code class="comments">// build the current Node </code></div><div class="line number26 index25 alt1"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">rootData = preorder[preIndex]; </code></div><div class="line number27 index26 alt2"><code class="undefined spaces">    </code><code class="plain">Node root = </code><code class="keyword">new</code> <code class="plain">Node(rootData); </code></div><div class="line number28 index27 alt1"><code class="undefined spaces">    </code><code class="plain">preIndex++; </code></div><div class="line number29 index28 alt2"><code class="undefined spaces"> </code> </div><div class="line number30 index29 alt1"><code class="undefined spaces">    </code><code class="comments">// find the node in inorderIndexMap </code></div><div class="line number31 index30 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(!inorderIndexMap.containsKey(rootData)) { </code></div><div class="line number32 index31 alt1"><code class="undefined spaces">      </code><code class="plain">notPossible[</code><code class="value">0</code><code class="plain">] = </code><code class="keyword">true</code><code class="plain">; </code></div><div class="line number33 index32 alt2"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="plain">root; </code></div><div class="line number34 index33 alt1"><code class="undefined spaces">    </code><code class="plain">} </code></div><div class="line number35 index34 alt2"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">inorderIndex = inorderIndexMap.get(rootData); </code></div><div class="line number36 index35 alt1"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(!(inStart <= inorderIndex </code></div><div class="line number37 index36 alt2"><code class="undefined spaces">          </code><code class="plain">&& inorderIndex <= inEnd)) { </code></div><div class="line number38 index37 alt1"><code class="undefined spaces">      </code><code class="plain">notPossible[</code><code class="value">0</code><code class="plain">] = </code><code class="keyword">true</code><code class="plain">; </code></div><div class="line number39 index38 alt2"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="plain">root; </code></div><div class="line number40 index39 alt1"><code class="undefined spaces">    </code><code class="plain">} </code></div><div class="line number41 index40 alt2"><code class="undefined spaces"> </code> </div><div class="line number42 index41 alt1"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">leftInorderStart = inStart, </code></div><div class="line number43 index42 alt2"><code class="undefined spaces">    </code><code class="plain">leftInorderEnd = inorderIndex - </code><code class="value">1</code><code class="plain">, </code></div><div class="line number44 index43 alt1"><code class="undefined spaces">    </code><code class="plain">rightInorderStart = inorderIndex + </code><code class="value">1</code><code class="plain">, </code></div><div class="line number45 index44 alt2"><code class="undefined spaces">    </code><code class="plain">rightInorderEnd = inEnd; </code></div><div class="line number46 index45 alt1"><code class="undefined spaces"> </code> </div><div class="line number47 index46 alt2"><code class="undefined spaces">    </code><code class="plain">root.left = buildTreeFromInorderPreorder( </code></div><div class="line number48 index47 alt1"><code class="undefined spaces">      </code><code class="plain">leftInorderStart, leftInorderEnd, preorder, </code></div><div class="line number49 index48 alt2"><code class="undefined spaces">      </code><code class="plain">inorderIndexMap, notPossible, preIndex); </code></div><div class="line number50 index49 alt1"><code class="undefined spaces"> </code> </div><div class="line number51 index50 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(notPossible[</code><code class="value">0</code><code class="plain">]) </code></div><div class="line number52 index51 alt1"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="plain">root; </code></div><div class="line number53 index52 alt2"><code class="undefined spaces"> </code> </div><div class="line number54 index53 alt1"><code class="undefined spaces">    </code><code class="plain">root.right = buildTreeFromInorderPreorder( </code></div><div class="line number55 index54 alt2"><code class="undefined spaces">      </code><code class="plain">rightInorderStart, rightInorderEnd, preorder, </code></div><div class="line number56 index55 alt1"><code class="undefined spaces">      </code><code class="plain">inorderIndexMap, notPossible, preIndex); </code></div><div class="line number57 index56 alt2"><code class="undefined spaces"> </code> </div><div class="line number58 index57 alt1"><code class="undefined spaces">    </code><code class="keyword">return</code> <code class="plain">root; </code></div><div class="line number59 index58 alt2"><code class="undefined spaces">  </code><code class="plain">} </code></div><div class="line number60 index59 alt1"><code class="undefined spaces"> </code> </div><div class="line number61 index60 alt2"><code class="undefined spaces">  </code><code class="keyword">static</code> <code class="keyword">boolean</code> <code class="plain">checkPostorderCorrect(Node root, </code></div><div class="line number62 index61 alt1"><code class="undefined spaces">                                       </code><code class="keyword">int</code><code class="plain">[] postorder, </code></div><div class="line number63 index62 alt2"><code class="undefined spaces">                                       </code><code class="keyword">int</code> <code class="plain">postIndex) </code></div><div class="line number64 index63 alt1"><code class="undefined spaces">  </code><code class="plain">{ </code></div><div class="line number65 index64 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(root == </code><code class="keyword">null</code><code class="plain">) </code></div><div class="line number66 index65 alt1"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="keyword">true</code><code class="plain">; </code></div><div class="line number67 index66 alt2"><code class="undefined spaces"> </code> </div><div class="line number68 index67 alt1"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(!checkPostorderCorrect(root.left, postorder, </code></div><div class="line number69 index68 alt2"><code class="undefined spaces">                               </code><code class="plain">postIndex)) </code></div><div class="line number70 index69 alt1"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="keyword">false</code><code class="plain">; </code></div><div class="line number71 index70 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(!checkPostorderCorrect(root.right, postorder, </code></div><div class="line number72 index71 alt1"><code class="undefined spaces">                               </code><code class="plain">postIndex)) </code></div><div class="line number73 index72 alt2"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="keyword">false</code><code class="plain">; </code></div><div class="line number74 index73 alt1"><code class="undefined spaces"> </code> </div><div class="line number75 index74 alt2"><code class="undefined spaces">    </code><code class="keyword">return</code> <code class="plain">(root.data == postorder[postIndex++]); </code></div><div class="line number76 index75 alt1"><code class="undefined spaces">  </code><code class="plain">} </code></div><div class="line number77 index76 alt2"><code class="undefined spaces"> </code> </div><div class="line number78 index77 alt1"><code class="undefined spaces">  </code><code class="keyword">static</code> <code class="keyword">boolean</code> <code class="plain">checktree(</code><code class="keyword">int</code><code class="plain">[] preorder, </code><code class="keyword">int</code><code class="plain">[] inorder, </code></div><div class="line number79 index78 alt2"><code class="undefined spaces">                           </code><code class="keyword">int</code><code class="plain">[] postorder, </code><code class="keyword">int</code> <code class="plain">N) </code></div><div class="line number80 index79 alt1"><code class="undefined spaces">  </code><code class="plain">{ </code></div><div class="line number81 index80 alt2"><code class="undefined spaces">    </code><code class="comments">// Your code goes here </code></div><div class="line number82 index81 alt1"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(N == </code><code class="value">0</code><code class="plain">) </code></div><div class="line number83 index82 alt2"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="keyword">true</code><code class="plain">; </code></div><div class="line number84 index83 alt1"><code class="undefined spaces"> </code> </div><div class="line number85 index84 alt2"><code class="undefined spaces">    </code><code class="plain">Map<Integer, Integer> inorderIndexMap </code></div><div class="line number86 index85 alt1"><code class="undefined spaces">      </code><code class="plain">= </code><code class="keyword">new</code> <code class="plain">HashMap<>(); </code></div><div class="line number87 index86 alt2"><code class="undefined spaces">    </code><code class="keyword">for</code> <code class="plain">(</code><code class="keyword">int</code> <code class="plain">i = </code><code class="value">0</code><code class="plain">; i < N; i++) </code></div><div class="line number88 index87 alt1"><code class="undefined spaces">      </code><code class="plain">inorderIndexMap.put(inorder[i], i); </code></div><div class="line number89 index88 alt2"><code class="undefined spaces"> </code> </div><div class="line number90 index89 alt1"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">preIndex = </code><code class="value">0</code><code class="plain">; </code></div><div class="line number91 index90 alt2"><code class="undefined spaces">    </code><code class="keyword">boolean</code><code class="plain">[] notPossible = </code><code class="keyword">new</code> <code class="keyword">boolean</code><code class="plain">[] { </code><code class="keyword">false</code> <code class="plain">}; </code></div><div class="line number92 index91 alt1"><code class="undefined spaces"> </code> </div><div class="line number93 index92 alt2"><code class="undefined spaces">    </code><code class="plain">Node root = buildTreeFromInorderPreorder( </code></div><div class="line number94 index93 alt1"><code class="undefined spaces">      </code><code class="value">0</code><code class="plain">, N - </code><code class="value">1</code><code class="plain">, preorder, inorderIndexMap, </code></div><div class="line number95 index94 alt2"><code class="undefined spaces">      </code><code class="plain">notPossible, preIndex); </code></div><div class="line number96 index95 alt1"><code class="undefined spaces"> </code> </div><div class="line number97 index96 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(notPossible[</code><code class="value">0</code><code class="plain">]) </code></div><div class="line number98 index97 alt1"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="keyword">true</code><code class="plain">; </code></div><div class="line number99 index98 alt2"><code class="undefined spaces"> </code> </div><div class="line number100 index99 alt1"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">postIndex = </code><code class="value">0</code><code class="plain">; </code></div><div class="line number101 index100 alt2"><code class="undefined spaces"> </code> </div><div class="line number102 index101 alt1"><code class="undefined spaces">    </code><code class="keyword">return</code> <code class="plain">checkPostorderCorrect(root, postorder, </code></div><div class="line number103 index102 alt2"><code class="undefined spaces">                                 </code><code class="plain">postIndex); </code></div><div class="line number104 index103 alt1"><code class="undefined spaces">  </code><code class="plain">} </code></div><div class="line number105 index104 alt2"><code class="undefined spaces"> </code> </div><div class="line number106 index105 alt1"><code class="undefined spaces">  </code><code class="keyword">public</code> <code class="keyword">static</code> <code class="keyword">void</code> <code class="plain">main(String[] args) </code></div><div class="line number107 index106 alt2"><code class="undefined spaces">  </code><code class="plain">{ </code></div><div class="line number108 index107 alt1"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">inOrder[] = { </code><code class="value">4</code><code class="plain">, </code><code class="value">2</code><code class="plain">, </code><code class="value">5</code><code class="plain">, </code><code class="value">1</code><code class="plain">, </code><code class="value">3</code> <code class="plain">}; </code></div><div class="line number109 index108 alt2"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">preOrder[] = { </code><code class="value">1</code><code class="plain">, </code><code class="value">2</code><code class="plain">, </code><code class="value">4</code><code class="plain">, </code><code class="value">5</code><code class="plain">, </code><code class="value">3</code> <code class="plain">}; </code></div><div class="line number110 index109 alt1"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">postOrder[] = { </code><code class="value">4</code><code class="plain">, </code><code class="value">5</code><code class="plain">, </code><code class="value">2</code><code class="plain">, </code><code class="value">3</code><code class="plain">, </code><code class="value">1</code> <code class="plain">}; </code></div><div class="line number111 index110 alt2"><code class="undefined spaces"> </code> </div><div class="line number112 index111 alt1"><code class="undefined spaces">    </code><code class="keyword">int</code> <code class="plain">len = inOrder.length; </code></div><div class="line number113 index112 alt2"><code class="undefined spaces"> </code> </div><div class="line number114 index113 alt1"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(checktree(preOrder, inOrder, postOrder, len)) </code></div><div class="line number115 index114 alt2"><code class="undefined spaces">      </code><code class="plain">System.out.println(</code><code class="string">"The tree is valid"</code><code class="plain">); </code></div><div class="line number116 index115 alt1"><code class="undefined spaces">    </code><code class="keyword">else</code></div><div class="line number117 index116 alt2"><code class="undefined spaces">      </code><code class="plain">System.out.println(</code><code class="string">"The tree is not valid"</code><code class="plain">); </code></div><div class="line number118 index117 alt1"><code class="undefined spaces">  </code><code class="plain">} </code></div><div class="line number119 index118 alt2"><code class="plain">} </code></div><div class="line number120 index119 alt1"><code class="undefined spaces"> </code> </div><div class="line number121 index120 alt2"><code class="comments">// This code is contributed by lokeshpotta20.</code></div></div></td></tr></tbody></table></div>

                    

Python3

# Python3 program for the above approach
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
  
  
preIndex = 0
notPossible = False
  
  
def buildTreeFromInorderPreorder(inStart, inEnd, preorder, inorderIndexMap):
    if(inStart > inEnd):
        return None
  
    # build the current node
    global preIndex
    global notPossible
    rootData = preorder[preIndex]
    root = Node(rootData)
    preIndex += 1
  
    # find the node in inorderIndexMap
    if(inorderIndexMap.get(rootData) == None):
        notPossible = True
        return root
  
    inorderIndex = inorderIndexMap.get(rootData)
    if((inStart <= inorderIndex and inorderIndex <= inEnd) == False):
        notPossible = True
        return root
  
    leftInorderStart = inStart
    leftInorderEnd = inorderIndex - 1
    rightInorderStart = inorderIndex + 1
    rightInroderEnd = inEnd
  
    root.left = buildTreeFromInorderPreorder(
        leftInorderStart, leftInorderEnd, preorder, inorderIndexMap)
  
    if(notPossible == True):
        return root
  
    root.right = buildTreeFromInorderPreorder(
        rightInorderStart, rightInroderEnd, preorder, inorderIndexMap)
  
    return root
  
  
postIndex = 0
  
  
def checkPostorderCorrect(root, postOrder):
    if(root == None):
        return True
    if(checkPostorderCorrect(root.left, postOrder) == False):
        return False
  
    if(checkPostorderCorrect(root.right, postOrder) == False):
        return False
  
    global postIndex
    if(root.data == postOrder[postIndex]):
        postIndex += 1
        return True
    else:
        postIndex += 1
        return False
  
  
def printPostorder(root):
    if(root == None):
        return
  
    printPostorder(root.left)
    printPostorder(root.right)
    print(root.data)
  
  
def printInorder(root):
    if(root == None):
        return
  
    printInorder(root.left)
    print(root.data)
    printInorder(root.right)
  
  
def checktree(preorder, inorder, postorder, N):
    if(N == 0):
        return True
    inorderIndexMap = {}
    for i in range(N):
        inorderIndexMap[inorder[i]] = i
  
    root = buildTreeFromInorderPreorder(0, N-1, preorder, inorderIndexMap)
  
    global notPossible
    if(notPossible == True):
        return False
  
    if(checkPostorderCorrect(root, postorder)):
        return True
    else:
        return False
  
  
# driver program
inOrder = [4, 2, 5, 1, 3]
preOrder = [1, 2, 4, 5, 3]
postOrder = [4, 5, 2, 3, 1]
  
len = len(inOrder)
  
# if both postorder traversal as same
if(checktree(preOrder, inOrder, postOrder, len) == True):
    print("Yes")
else:
    print("No")
  
# THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999)

                    

C#

using System;
using System.Collections.Generic;
  
class Node
{
    public int data;
    public Node left;
    public Node right;
  
    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}
  
class Program
{
    static Node BuildTreeFromInorderPreorder(int inStart, int inEnd, int[] preorder, Dictionary<int, int> inorderIndexMap, ref bool notPossible, ref int preIndex)
    {
        if (inStart > inEnd)
            return null;
  
        // Build the current node
        int rootData = preorder[preIndex];
        Node root = new Node(rootData);
        preIndex++;
  
        // Find the node in inorderIndexMap
        if (!inorderIndexMap.ContainsKey(rootData))
        {
            notPossible = true;
            return root;
        }
  
        int inorderIndex = inorderIndexMap[rootData];
        if (!(inStart <= inorderIndex && inorderIndex <= inEnd))
        {
            notPossible = true;
            return root;
        }
  
        int leftInorderStart = inStart;
        int leftInorderEnd = inorderIndex - 1;
        int rightInorderStart = inorderIndex + 1;
        int rightInorderEnd = inEnd;
  
        root.left = BuildTreeFromInorderPreorder(leftInorderStart, leftInorderEnd, preorder, inorderIndexMap, ref notPossible, ref preIndex);
  
        if (notPossible)
            return root;
  
        root.right = BuildTreeFromInorderPreorder(rightInorderStart, rightInorderEnd, preorder, inorderIndexMap, ref notPossible, ref preIndex);
  
        return root;
    }
  
    static bool CheckPostorderCorrect(Node root, int[] postorder, ref int postIndex)
    {
        if (root == null)
            return true;
  
        if (!CheckPostorderCorrect(root.left, postorder, ref postIndex))
            return false;
  
        if (!CheckPostorderCorrect(root.right, postorder, ref postIndex))
            return false;
  
        return (root.data == postorder[postIndex++]);
    }
  
    static bool CheckTree(int[] preorder, int[] inorder, int[] postorder, int N)
    {
        if (N == 0)
            return true;
  
        Dictionary<int, int> inorderIndexMap = new Dictionary<int, int>();
        for (int i = 0; i < N; i++)
            inorderIndexMap.Add(inorder[i], i);
  
        int preIndex = 0;
        bool notPossible = false;
  
        Node root = BuildTreeFromInorderPreorder(0, N - 1, preorder, inorderIndexMap, ref notPossible, ref preIndex);
  
        if (notPossible)
            return false;
  
        int postIndex = 0;
  
        return CheckPostorderCorrect(root, postorder, ref postIndex);
    }
  
     static void Main(string[] args)
  {
    int[] inOrder = { 4, 2, 5, 1, 3 };
    int[] preOrder = { 1, 2, 4, 5, 3 };
    int[] postOrder = { 4, 5, 2, 3, 1 };
  
    int len = inOrder.Length;
  
    if (CheckTree(preOrder, inOrder, postOrder, len))
      Console.WriteLine("Yes");
    else
      Console.WriteLine("No");
  }
}

                    

Javascript

// JavaScript program for the above approach
class Node{
    constructor(val){
        this.data = val;
        this.left = null;
        this.right =  null;
    }
}
  
let preIndex = 0;
let notPossible = false;
function buildTreeFromInorderPreorder(inStart, inEnd, 
preorder, inorderIndexMap){
    if(inStart > inEnd){
        return null;
    }
      
    // build the current node
    let rootData = preorder[preIndex];
    let root = new Node(rootData);
    preIndex++;
      
    // find the node in inorderIndexMap
    if(inorderIndexMap.has(rootData) == false){
        notPossible = true;
        return root;
    }
      
    let inorderIndex = inorderIndexMap.get(rootData);
    if(!(inStart <= inorderIndex && inorderIndex <= inEnd)){
        notPosstible = true;
        return root;
    }
      
    let leftInorderStart = inStart;
    let leftInorderEnd = inorderIndex - 1;
    let rightInorderStart = inorderIndex + 1;
    let rightInorderEnd = inEnd;
          
    root.left = buildTreeFromInorderPreorder(
        leftInorderStart, leftInorderEnd, preorder, inorderIndexMap);
          
    if(notPossible == true)
        return root;
      
    root.right = buildTreeFromInorderPreorder(
        leftInorderStart, leftInorderEnd, preorder, inorderIndexMap);
      
    return root;
}
  
let postIndex = 0;
function checkPostorderCorrect(root, postOrder){
    if(root == null) return true;
    if(!checkPostorderCorrect(root.left, postOrder))
        return false;
      
    if(!checkPostorderCorrect(root.right, postOrder))
        return false;
          
    return (root.data == postOrder[postIndex++]);
}
  
function printPostorder(root){
    if(root == null) return;
      
    printPostorder(root.left);
    printPostorder(root.right);
    document.write(root.data + " ");
}
  
function printInorder(root){
    if(root == null) return;
    printInorder(root.left);
    document.write(root.data + " ");
    printInorder(root.right);
}
  
function checktree(preorder, inorder, postorder, N){
    if(N == 0) return true;
      
    inorderIndexMap = new Map();
    for(let i = 0; i<N; i++){
        inorderIndexMap.set(inorder[i], i);
    }
      
    let root = buildTreeFromInorderPreorder(0, N-1, 
    preorder, inorderIndexMap);
      
    if(notPossible == true) return false;
      
    return checkPostorderCorrect(root, postorder);
}
  
// driver program
let inOrder = [4, 2, 5, 1, 3];
let preOrder = [1, 2, 4, 5, 3];
let postOrder = [4, 5, 2, 3, 1];
  
let len = inOrder.length;
  
// If both postorder traversals as same
if(checktree(preOrder, inOrder, postOrder, len))
    document.write("Yes");
else
    document.write("No");
      
// This code is contributed  by Yash Agarwal(yashagarwal2852002)

                    

Output
Yes

Time Complexity: O(N)
Auxiliary Space: O(N), where N is number of nodes in the tree.



Last Updated : 06 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads