algorithm - How do I construct a non-binary tree based on the preorder&inorder or postorder&inorder traversal? -


two of exercises data structures , algorithms class sound this

construct tree preorder traversal is: 1, 2, 5, 3, 6, 10, 7, 11, 12, 4, 8, 9, , inoder traversal 5, 2, 1, 10, 6, 3, 11, 7, 12, 8, 4, 9.

construct tree postorder traversal is: 5, 2, 10, 6, 11, 12, 7, 3, 8, 9, 4, 1, , inoder traversal 5, 2, 1, 10, 6, 3, 11, 7, 12, 8, 4, 9.

i have draw structure of tree, without implementing in programming language. thing makes tasks harder trees not binary trees. techniques use build trees?

i'm not sure can give precise algorithmic solution this, can give conceptual 1 should sufficient. think if fine-tune well-defined algorithm useful , make (that part of) midterm trivial.

first, think how inorder traversal traverses tree. if draw tree leftmost child left (visually) , other children right (visually) inorder traversal loosely goes left right. might run issue it's not quite left right (because of overlap between child of 1 node , parent or that) can stretch tree out make "left right". take advantage of starting tree inorder traversal:

5 2 1 10 6 3 11 7 12 8 4 9 

then idea move nodes , down according preorder traversal. part hard define part. move nodes if they're visited "earlier" , move them down if they're visited later. so, instance, 1 left of 2 , 5 in preorder traversal raised "up" in sense made 2 , 5 ancestors (but not children) of 1. like

   1 5 2 10 6 3 11 7 12 8 4 9 

then see 2 comes before 5, raised 2:

    1   2  5     10 6 3 11 7 12 8 4 9 

then see 3 comes before 6 , 10 in preorder traversal can "raise" it.

    1   2        3 5     10 6   11 7 12 8 4 9 

and on. note 3 child of 2 or 1... tree satisfies above constraints isn't unique.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -