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

文章目录

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值