tree - GIven a level order FInd BST -
given bst level-order traversal is:
99 65 53 80 22 62 98 21 49 82 36 51
what tree if make tree following level order traversal?
here's how arrived @ bst present @ bottom.
the main governing rule 1 has apply bst: if "order" elements, every node in left subtree of node has considered "before" node, , every node in right subtree has considered "after" node.
since list numbers, , nothing more rules ordering, numerical ordering assumed.
as such, when placing nodes have find correct location of each node given following procedure:
- decide if can find place on current level (if there room more nodes there). find find places place if didn't care bst rule. check each such position see if legal position. there should one.
- if find such place, place there, if not, go next level , place in leftmost legal position there.
- when placing more nodes on existing level, go left right.
so here's runthrough of given numbers:
- the first level contains 1 number, 99.
- the second level can contain 1 or 2 numbers, 65 has here perhaps 53 not. since 65 less 99 has placed down-left 99. can 53 placed down-right 99? no, has on third level.
- so 53 on third level, , has down-left 65.
- what 80? either on third level, down-right 65, or on fourth line. can on fourth line? either have less 53, or greater 53 , smaller 65. greater 65 cannot on fourth level has on third, down-right 65.
- next comes 22, , less 65, since we're starting level 4 easy place, has placed down-right 53.
- next up, 62, since still within range of level above can have under it, have find right place it. since greater 53, not greater 65, has placed down-right 53.
- 98 greater 80. since still less 99, still has place in main left subtree of 99 place down-right 80.
- 21 down-left 22.
- 49 less 53, greater 22, placed down-right 22.
- 82 has either placed down-left or down-right 62, down-left or down-right 98, or start new line. legal position in line down-left 98.
- 36 greater 21, not greater 49, has placed either down-right 21 or down-left 49. since 36 greater 22, has down-left 49.
- the final number 51 greater 51, not greater 53, has placed somewhere in left subtree of 53, , place down-right 49.
final bst:
99 / 65 / \ 53 80 / \ \ 22 62 98 / \ / 21 49 82 / \ 36 51
Comments
Post a Comment