solution.md 1.6 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 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 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 88 89 90 91 92 93 94 95 96 97
# 从中序与后序遍历序列构造二叉树

<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

```cpp
#include <bits/stdc++.h>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution
{
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
    {
        if (0 == inorder.size() || 0 == postorder.size())
        {
            return NULL;
        }
        return build(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
    }

    TreeNode *build(vector<int> &inorder, int i1, int i2, vector<int> &postorder, int p1, int p2)
    {
        TreeNode *root = new TreeNode(postorder[p2]);
        int i = i1;
        while (i <= i2 && postorder[p2] != inorder[i])
        {
            i++;
        }
        int left = i - i1;
        int right = i2 - i;
        if (left > 0)
        {
            root->left = build(inorder, i1, i - 1, postorder, p1, p1 + left - 1);
        }
        if (right > 0)
        {
            root->right = build(inorder, i + 1, i2, postorder, p1 + left, p2 - 1);
        }
        return root;
    }
};

```

## 答案

```cpp

```

## 选项

### A

```cpp

```

### B

```cpp

```

### C

```cpp

```