Reputation: 290
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
Reputation: 175
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
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:
Inorder: 1 2 4 6
Level: 4 2 6 1
4
1 2
6
Result:
8
/ 9 10
4
2 1 \
6
Inorder: 1 2
Level: 2 1
2
1
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