1

I'm working on a coding question and right now I'm bit confused. If I'm given an array which represents level order traversal of a binary tree. How do I construct a tree from that?

So far here is my thought process so far: I know the 0th index is the root, leftChild = 2*i+1 and rightChild = 2*i+2.

Here is what I have so far and I don't think its right:

public Tree buildTree(ArrayList<Tree> arr, int i) {
    if (i > list.size() - 1) {
        return null;
    }

    root = list.get(i);
    root.LeftChild = buildTree(arr, 2*i+1);
    root.RightChild = buildTree(arr, 2*i+2);

    return root;
}

my i starts at 0, Thanks.

1
  • Can you provide link to the question ? Commented Oct 29, 2018 at 1:38

2 Answers 2

2

Your code would only work with complete binary trees, a special case of binary trees.

You can't construct generic binary tree just from the level order traversal.

You need two traversal of which one must be an inorder traversal.

Following combination can uniquely identify a tree.

  • Inorder and Preorder.
  • Inorder and Postorder.
  • Inorder and Level-order.

Though there is a possibility to construct tree (given only level order traversal) if you've some separators in the given array like described in this post.

Sign up to request clarification or add additional context in comments.

2 Comments

It is a complete binary tree
@RockySingh your code seems to work fine for complete binary tree. Did you tried the edge cases like tree with 0,1, half complete, fully complete nodes?
0

Your code seems fine...although it's strange that your method takes in an ArrayList<Tree> instead of an ArrayList<Node>. Why don't you think it's right? How are you testing your method? What kind of errors are you getting?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.