Lexy Feito
Lexy Feito

Reputation: 290

Construct binary tree from inorder and level traversal

Need help finding a way to construct a binary tree given the inorder and level traversal. Is it possible to do it using recursion since the level traversal has to be done by using a queue?

Upvotes: 3

Views: 2114

Answers (1)

Reservedegotist
Reservedegotist

Reputation: 175

Here's how you can approach this problem. It's easier to think of how to approach each step by looking from reverse:

      8
     / \
    4   9
   / \   \
  2   6   10
 /
1

You have the following:

Inorder: 1 2 4 6 8 9 10

Level: 8 4 9 2 6 10 1

Level 1 - Root

A level traversal is a left to right, top to down traversal of the tree (like breadth-first search). In this example, you know that 8 will be the root node. Now looking at the inorder traversal, we know that 1 2 4 6 make up the left subtree and 9 10 make the right subtree. So we have:

        8
1 2 4 6   9 10

While preserving order, create a copy of the level traversal without the nodes we are going to visit for the left and right recursive construction. Below notes will go through the left tree steps and what is passed through:

Level 2 - Left Subtree

Inorder: 1 2 4 6

Level: 4 2 6 1

  • Root: 4
  • Left subtree: 1 2
  • Right subtree: 6

Result:

        8
       /  9 10
      4
  2 1  \
        6

Level 3 - Left Subtree

Inorder: 1 2

Level: 2 1

  • Root: 2
  • Left subtree: 1
  • Right subtree: empty

Result:

       8
      /  9 10
     4
    / \   
   2   6
  /
 1

Now that we're done recursing all the way left, hopefully you can walk through on how to deal with the right children of the tree! Once you have the algorithm, you should be able to construct back the tree given two different traversals. The key is to recognize based on the two traversals how to determine the root at each recursive call, and the rest should follow through.

Upvotes: 3

Related Questions