DEV Community

Thivyaa Mohan
Thivyaa Mohan

Posted on

2 2

Construct a Binary Tree from Inorder and Postorder

When we are given a root,left and right subtree :

Inorder : Left Root Right
Preorder : Root Left Right

We can get the root from the Preorder traversal, and the first element from the Preorder traversal is Root.If we locate the root, we can find the left and right side of the tree easily. We can follow the similar fashion and construct the whole tree.

Here is the code of the solution

class Solution{
    public:
    int order=0;
    Node* build(int in[],int pre[],int s,int e){
        if(s>e){
            return NULL;
        }
        Node* root=new Node(pre[order++]);
        int index=0;
        for(int i=s;i<=e;i++){
            if(in[i]==root->data){
                index=i;
                break;
            }
        }
        root->left=build(in,pre,s,index-1);
        root->right=build(in,pre,index+1,e);
        return root;
    }
    Node* buildTree(int in[],int pre[], int n)
    {
        return build(in,pre,0,n-1);
        // Code here
    }
};

Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay