目录

LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal(由中序和后序遍历建立二叉树)

目录

Given inorder and postorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

For example, given

1
2
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

1
2
3
4
5
    3
   / \
  9  20
    /  \
   15   7

解:

 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

/*
 * @lc app=leetcode id=106 lang=cpp
 *
 * [106] Construct Binary Tree from Inorder and Postorder Traversal
 */
/**
 * 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:

    // 后序的最后一个节点为根节点,在中序遍历中找出根节点,根节点前的所有节点为左子树,根节点后的所有节点为右子树。
    // is inorder 的起始位置
    // ie inorder 的结束位置
    // ps postorder 的起始位置
    // pe postorder 的结束位置
    TreeNode* create(vector<int> &inorder, vector<int> &postorder, int is, int ie, int ps, int pe) {
        if(ps > pe){
            return nullptr;
        }
        TreeNode* node = new TreeNode(postorder[pe]);
        int iRootS; // inorder 根节点位置
        for(int i = is; i <= ie; i++){
            if(inorder[i] == node->val){
                iRootS = i;
                break;
            }
        }
        int leftMarginLen = iRootS - is - 1;  // 左位置间距长度,可0,即只有一个节点
        int rightMarginLen = ie - iRootS - 1; // 右位置间距长度,可0
        node->left = create(inorder, postorder, is, iRootS - 1, ps, ps + leftMarginLen);
        int pSubLen = pe - 1; //两个子树总节点长度
        node->right = create(inorder, postorder, iRootS + 1, ie, pSubLen - rightMarginLen, pSubLen);
        return node;
    }

    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        return create(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
    }

};