题目描述链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
解题思路:其基本思路同题目:从前序与中序遍历序列构造二叉树 的基本思路一致,采用递归法,将大问题
化为小问题。即得到左子树与右子树的序列的中序序列和后序序列继续递归的构造。
其LeetCode C++ 求解代码如下:
/** * 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: unordered_map<int,int>index;//获取其在中序序列中的位置 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { int len=inorder.size(); for(int i=0;i<len;++i){ index[inorder[i]]=i; } return myTree(inorder,postorder,0,len-1,0,len-1); } TreeNode* myTree(vector<int>& inorder ,vector<int>& postorder,int in_left,int in_right,int post_left,int post_right){ if(post_left>post_right){ return NULL; } int temp=postorder[post_right]; TreeNode* root=new TreeNode(temp); int size=index[temp]-in_left; root->left=myTree(inorder,postorder,in_left,index[temp]-1,post_left,post_left+size-1); root->right=myTree(inorder,postorder,index[temp]+1,in_right,post_left+size,post_right-1); return root; } };