When to use Preorder, Postorder, and Inorder Binary Search Tree Traversal strategies

前端 未结 5 1377
萌比男神i
萌比男神i 2020-12-12 08:47

I realized recently that while having used BST\'s plenty in my life, I\'ve never even contemplated using anything but Inorder traversal (while I am aware of and know how eas

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 09:07

    There are tons of places you see this difference play a real role.

    One great one I'll point out is in code generation for a compiler. Consider the statement:

    x := y + 32
    

    The way you would generate code for that is (naively, of course) to first generate code for loading y into a register, loading 32 into a register, and then generating an instruction to add the two. Because something has to be in a register before you manipulate it (let's assume, you can always do constant operands but whatever) you must do it this way.

    In general, the answers you can get to this question basically reduce to this: the difference really matter when there is some dependence between processing different parts of the data structure. You see this when printing the elements, when generating code (external state makes the difference, you can view this monadically as well, of course), or when doing other types of calculations over the structure that involve computations depending on the children being processed first.

提交回复
热议问题