Pre-order to post-order traversal

后端 未结 11 1490
挽巷
挽巷 2020-12-23 21:56

If the pre-order traversal of a binary search tree is 6, 2, 1, 4, 3, 7, 10, 9, 11, how to get the post-order traversal?

11条回答
  •  [愿得一人]
    2020-12-23 22:30

    Since, it is a binary search tree, the inorder traversal will be always be the sorted elements. (left < root < right)

    so, you can easily write its in-order traversal results first, which is : 1,2,3,4,6,7,9,10,11

    given Pre-order : 6, 2, 1, 4, 3, 7, 10, 9, 11

    In-order : left, root, right Pre-order : root, left, right Post-order : left, right, root

    now, we got from pre-order, that root is 6.

    now, using in-order and pre-order results: Step 1:

                 6
                / \
               /   \
              /     \
             /       \
       {1,2,3,4}  {7,9,10,11}
    

    Step 2: next root is, using in-order traversal, 2:

                 6
                / \
               /   \
              /     \
             /       \
            2  {7,9,10,11}
           / \
          /   \
         /     \
        1    {3,4}
    

    Step 3: Similarly, next root is 4:

                 6
                / \
               /   \
              /     \
             /       \
            2  {7,9,10,11}
           / \
          /   \
         /     \
        1       4
               /
              3
    

    Step 4: next root is 3, but no other element is remaining to be fit in the child tree for "3". Considering next root as 7 now,

                 6
                / \
               /   \
              /     \
             /       \
            2         7
           / \         \
          /   \       {9,10,11}
         /     \
        1       4
               /
              3
    

    Step 5: Next root is 10 :

                 6
                / \
               /   \
              /     \
             /       \
            2         7
           / \         \
          /   \         10
         /     \       /  \
        1       4     9   11
               /
              3
    

    This is how, you can construct a tree, and finally find its post-order traversal, which is : 1, 3, 4, 2, 9, 11, 10, 7, 6

提交回复
热议问题