Search code examples
recursiontreebinary-search-treepreorder

Rebuild BST from preorder, error in logic


Trying to wrap my head around how to correct my code. I have the idea up, but I get stuck during the implementation.

when I step through the code below, I can reconstruct part of the BST from a pre-order traversal. But at some point, I will have function call like:

recon(preOrd,2,2) 

which results in a leaf not being assigned. I do yet know how to correct this.

I have seen other threads on this topic, but want to iron out my issue so I can really learn this concept of rebuilding the BST.

public static Node recon(int[] preOrd,int start,int end){

if (start==end){
        return null;
    }
    Node root = new Node (preOrd[start]);   
    int div=start;
    for (i=start+1;i<=end && preOrd[i]<preOrd[start];i++){ 
        div=i;
    }
Node left= reconstruct(preOrd,start+1,div);
Node right= reconstruct(preOrd,div+1,end);

root.setLeft= left;
root.setRight=right;
    return root;
}

Solution

  • Turns out this is pretty straightforward. Just needed to correct my thinking on the updating of leaf nodes..

    public static Node recon(int[] preOrd,int start,int end){
        Node root = new Node (preOrd[start]);//declare the new node      
        if (start>end){ //this is illegal, so return null 
                return null;
            }
        if (start==end){
                return root;
            }  
            int div=start;
            for (int i=start+1;i<=end preOrd[i]<preOrd[start];i++){ 
                div=i;
            }
        Node left= reconstruct(preOrd,start+1,div);
        Node right= reconstruct(preOrd,div+1,end);
    
        root.setLeft= left;
        root.setRight=right;
        return root;
        }