Create Tree (Using Postorder and Inorder) Can you help me in debugging

import java.util.*;
public class Main {

static Scanner scn = new Scanner(System.in);

public static void main(String[] args) {
	Main m = new Main();
	int[] post = takeInput();
	int[] in = takeInput();
	BinaryTree bt = m.new BinaryTree(post, in);
	bt.display();
}

public static int[] takeInput() {
	int n = scn.nextInt();

	int[] rv = new int[n];
	for (int i = 0; i < rv.length; i++) {
		rv[i] = scn.nextInt();
	}

	return rv;
}

private class BinaryTree {
	private class Node {
		int data;
		Node left;
		Node right;
	}

	private Node root;
	private int size;

	public BinaryTree(int[] post, int[] in) {
		this.root = this.construct(post, 0, post.length - 1, in, 0, in.length - 1);
	}

	private Node construct(int[] post, int plo, int phi, int[] in, int ilo, int ihi) {
            if(ilo>ihi){
                return null;
            }
               Node nn = new Node();
               nn.data = post[phi];
               phi--;
            if(ilo==ihi){
               
               return nn;
            }
            
            int i =ilo;
            for(;i<ihi;i++){
                if(nn.data == in[i]){
                    break;
                }
            }
     
          

        
        nn.right = construct(post,plo,phi,in,i+1,ihi);
        nn.left = construct(post,plo,phi,in,ilo,i-1); // If i put phi-1 then it gives correct output but why is that so
       
        return nn;
	}

	public void display() {
		this.display(this.root);
	}

	private void display(Node node) {
		if (node == null) {
			return;
		}

		String str = "";

		if (node.left != null) {
			str += node.left.data;
		} else {
			str += "END";
		}

		str += " => " + node.data + " <= ";

		if (node.right != null) {
			str += node.right.data;
		} else {
			str += "END";
		}

		System.out.println(str);

		this.display(node.left);
		this.display(node.right);
	}

}

}

Hi Vaibhav,
First if plo > phi then you have to return null. Also after finding index of element of post array at index phi in in array, you have to create one variable say nel which is equal to index - ilo in order to divide the post and in array in a right way for left and right formation of tree. Now while making call for left formation of tree the value of phi will be pass as plo + nel - 1 because see we want only that part of postorder array that contains left portion of tree. Also while making call for right formation of tree the value of plo will be pass as plo + nel and value of phi as phi - 1 for the same reason we had pass the value of phi while making call for left portion.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.