solution.md 1.4 KB
Newer Older
ToTensor's avatar
ToTensor 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# 从中序与后序遍历序列构造二叉树

<p>根据一棵树的中序遍历与后序遍历构造二叉树。</p>

<p><strong>注意:</strong><br>
你可以假设树中没有重复的元素。</p>

<p>例如,给出</p>

<pre>中序遍历 inorder =&nbsp;[9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]</pre>

<p>返回如下的二叉树:</p>

<pre>    3
   / \
  9  20
    /  \
   15   7
</pre>


## template

```python

ToTensor's avatar
ToTensor 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        def build_tree(in_left, in_right, post_left, post_right):
            if in_left > in_right:
                return

            post_root = post_right

            root = TreeNode(postorder[post_root])

            in_root = inorder_map[root.val]

            size_of_left = in_root - in_left

            root.left = build_tree(
                in_left, in_root - 1, post_left, post_left + size_of_left - 1
            )

            root.right = build_tree(
                in_root + 1, in_right, post_left + size_of_left, post_root - 1
            )

            return root

        size = len(inorder)

        inorder_map = {}

        for i in range(size):
            inorder_map[inorder[i]] = i

        return build_tree(0, size - 1, 0, size - 1)

ToTensor's avatar
ToTensor 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

```

## 答案

```python

```

## 选项

### A

```python

```

### B

```python

```

### C

```python

```