LeetCode106—Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:python 字符串格式化 编辑:程序博客网 时间:2024/05/15 13:16

LeetCode106—Construct Binary Tree from Inorder and Postorder Traversal

原题

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

后序遍历和中序遍历建立数

分析

跟LeetCode—105类似,后序遍历从后往前,要先递归右子树再递归左子树。

代码

class Solution {private:    TreeNode* helper(vector<int>&inorder, vector<int>&postorder, map<int, int>&index,int pstart,int pend,int instart,int inend)    {        if (instart > inend)            return NULL;        int rootval = postorder[pend];        int rootindex = index[rootval];        TreeNode*root = new TreeNode(rootval);        root->right = helper(inorder, postorder, index, pend-inend+rootindex, pend - 1, rootindex + 1, inend);        root->left = helper(inorder, postorder, index, pstart, pend - inend + rootindex-1, instart,rootindex-1);        return root;    }public:    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {        map<int, int>index;        for (int i = 0; i < inorder.size(); i++)        {            index[inorder[i]] = i;        }        return helper(inorder, postorder, index, 0, postorder.size() - 1, 0, inorder.size() - 1);    }};
1 0