3
votes

Given the level order traversal of a complete binary tree in an array, how to store the inorder traversal of the said tree in the given array, without building up the tree. This is what I came up with.

void recurse (int *inp, int size_array, int *output, int iter_a, int &iter_b)
{
    if (iter_a>=size_array)
        return;

    recurse (inp,size_array,output,2*iter_a+1,iter_b);


    output[iter_b] = inp[iter_a];
    iter_b++;


    recurse (inp,size_array,output,2*iter_a+2,iter_b);

}

Is there an in-place non-recursive O(n) solution for the said problem?

2

2 Answers

1
votes

this is the function that i created to store the inorder traversal in array e from levelorder traversal of array a,n is length of array a.Set initial k=0 and x=0.

void convert(long long int a[],long long int e[],long long int n,long long int k,long long int x)
{
    if((2*k+1)>=n||(2*k+2)>=n)
        return;
    convert(a,e,n,2*k+1,x);
    e[x]=a[k];
    x++;
    convert(a,e,n,2*k+2,x);

    return;
}
0
votes

This is a iterative solution for converting level order to inorder but not inplace

private class Entry{
    int data;
    int pos;

    Entry(int data, int pos){
        this.data = data;
        this.pos = pos;
    }
}

public void convertLevelToInorder(int[] levelOrder){

    // nodes are stored from index 1

    int len = levelOrder.length;
    int[] inOrder = new int[len];

    Stack<Entry> stack = new Stack<Entry>();

    int pos = 1;
    int count = 1;

    while(!stack.isEmpty() || pos < len){

        while(pos < len && levelOrder[pos] != -1 ){
            stack.push(new Entry(levelOrder[pos],pos));
            pos = pos*2;
        }

        Entry e = stack.pop();
        inOrder[count++] = e.data;
        pos = e.pos*2+1;
    }

    for(int i=1;i<len;i++)
        System.out.print(inOrder[i] + "  ");
    System.out.println();
}