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.

/**
 * 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 {
private:
        unordered_map<int, int> inm; // inorder map [inorder[i], i]
        // 声明一个无序的map(用hash函数组织的map),关键字为中序遍历值
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n = inorder.size(), i = 0;   // 获取结点的个数赋值给n
        for(auto val: inorder) 
            inm[val] = i++; // build inm for dfs 将中序遍历的结果存入map中
        
        return dfs(inorder, 0, n - 1, postorder, 0, n - 1); // 调用dfs函数遍历
    }
    
    TreeNode* dfs(vector<int>& inorder, int ileft, int iright, vector<int>& postorder, int pleft, int pright) {
        if(ileft > iright) return nullptr; // 当前中序遍历的指示索引,左大于右
        
        int val = postorder[pright]; // root value 后序遍历的最后一个元素是根节点的值
        TreeNode *root = new TreeNode(val);// 建立一个根节点,其值为后序遍历的最后一个值
        if(ileft == iright) return root;   // 如果左子树只剩一个结点
        
        int iroot = inm[val];    // 将中序遍历中根节点的值处于的索引值取出以便确定左右子树在两个遍历中的位置
        int nleft = iroot - ileft; // length of left subtree 根节点的索引减去最左边的索引为左子树的长度
        root->left = dfs(inorder, ileft, iroot - 1, postorder, pleft, pleft + nleft - 1);
        // 找出中序遍历和后序遍历中的左子树部分,寻找左子树的根节点
        root->right = dfs(inorder, iroot + 1, iright, postorder, pleft + nleft, pright - 1);
        // 找出中序遍历和后序遍历中的右子数部分,寻找右子树的根节点
        return root;  // 返回根节点
    }
};
原文地址:https://www.cnblogs.com/simplepaul/p/6732678.html