# 106. Construct Binary Tree from Inorder and Postorder Traversal

## 1.問題&#x20;

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LOSWpDeKKzRSEn0doCN%2F-LOSZUzhfTMAVimGMjbN%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-10-10%20%E4%B8%8B%E5%8D%886.41.26.png?alt=media\&token=c2a861fc-02a6-4b70-a9d5-663ee85cc842)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 確認題意:  root是NULL是true或false?
* function header, parameter
* r input
* 說明想法
  * 想法與105題相同, 由於postorder序列建構tree, 必須由序列的最後往前
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
/**
 * Definition for a binary tree node.
 * 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) {
        int pos = postorder.size() - 1;
        return buildBinary(inorder, postorder, 0, postorder.size() - 1, pos);
    }
private:
    TreeNode* buildBinary(vector<int>& inorder, vector<int>& postorder, int left, int right, int& pos) {
        if (pos < 0 || left > right) {
            return NULL;
        }
        int i = 0;
        for (i = left; i <= right; i++) {
            if (inorder[i] == postorder[pos]){
                break;
            }
        }
        TreeNode* node = new TreeNode(postorder[pos]);
        pos--;
        node->right = buildBinary(inorder, postorder, i + 1, right, pos);
        node->left = buildBinary(inorder, postorder, left, i - 1, pos);
        
        return node;
    }
};
```
