Retrieve a binary tree from its pre-order and in-order representations

文章目录

  • Problem
  • Solution
  • Example

Problem

Given the Pre-order tranversal & In-order tranversal, retrieve the original tree.

Solution

Divide-and-conquer

  • Divide the original tree into root, left subtree, right subtree.
  • Do this recursively for every subtree.

Example

Pre-order: 3, 4, 0, 1, 5, 2, 6, 7
In-order: 4, 3, 1, 5, 0, 2, 7, 6

  1. From the pre-order, we conclude 3 is the root
  2. Locate 3 in the in-order.
    • Left subtree contains 4 (leaf node)
    • Right subtree contains 1, 5, 0, 2, 7, 6
    • Inorder-based-representation: [4] 3 [1 5 0 2 7 6]
Visualization:
        3
       / \
      4  [1 5 0 2 7 6]
  1. Look at the right subtree [1 5 0 2 7 6]
    • Its pre-order traversal: [0 1 5 2 6 7]
    • root is 0, left subtree [1 5], right subtree [2 6 7]
    • partial representation: [1 5] 0 [2 7 6]
    • the whole tree: [4] 3 [ [1 5] 0 [2 7 6] ]
Visualization:
        3
       / \
      4   0
         / \
     [1 5] [2 7 6]
  1. Look at left subtree [1 5]
    • Pre-order traversal: [1 5]
    • root is 1, left subtree empty, right subtree [5]
    • partial representation: 1 [5]
    • the whole tree: [4] 3 [ [ 1 [5] ] 0 [2 7 6] ]
Visualization:
        3
       / \
      4   0
         / \
        1  [2 7 6]
         \
          5
  1. Look at right subtree [2 7 6]
    • Pre-order traversal: [2 6 7]
    • root is 2, left subtree empty, right subtree [7 6]
    • partial representation: 2 [7 6]
    • the the whole tree: [4] 3 [ [ 1 [5] ] 0 [ 2 [7 6] ] ]
Visualization:
        3
       / \
      4   0
         / \
        1   2
         \   \
          5  [7 6]
  1. Look at right subtree [7 6]
    • Pre-order traversal: [6 7]
    • root is 6, left subtree [7], right subtree empty
    • partial representation: [7] 6
    • the the whole tree: [4] 3 [ [ 1 [5] ] 0 [ 2 [ [7] 6 ] ] ]
Visualization:
        3
       / \
      4   0
         / \
        1   2
         \   \
          5   6
             /
            7

你可能感兴趣的:(Algorithm,二叉树,逆向)