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?
-
Constructing and traversing are slightly different. Which one did you want to focus on?Makoto– Makoto2013年03月14日 02:01:06 +00:00Commented Mar 14, 2013 at 2:01
-
Constructing, i know how to do the traversal by level but cant seem to find a way to construct a tree from the inorder and level traversalsLexy Feito– Lexy Feito2013年03月14日 02:03:55 +00:00Commented Mar 14, 2013 at 2:03
-
Again - traversal and construction are different. Show us what kind of code you have and we can start from there. Be sure to edit it into the post.Makoto– Makoto2013年03月14日 02:04:47 +00:00Commented Mar 14, 2013 at 2:04
-
This is what i have inorder (2 4 1 3 5) and level (1 2 3 4 5) how would you construct a tree from that?Lexy Feito– Lexy Feito2013年03月14日 02:07:25 +00:00Commented Mar 14, 2013 at 2:07
-
Both trees are going to be wildly different. (Also, that's not code. Do you have what you've tried?)Makoto– Makoto2013年03月14日 02:16:22 +00:00Commented Mar 14, 2013 at 2:16
1 Answer 1
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.