后序与中序得原二叉树,与上篇类似。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode *buildTree(vector &inorder, vector &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function return build(inorder,postorder,inorder.size(),0,postorder.size()-1); } TreeNode* build(vector &inorder,vector &postorder,int size,int i,int p) { if(size==0) return NULL; TreeNode* head = (TreeNode*)malloc(sizeof(TreeNode)); head->val = postorder[p]; int j; for(j=i;j left = build(inorder,postorder,j-i,i,p-size+(j-i)); head->right = build(inorder,postorder,size-(j-i)-1,j+1,p-1); return head; }};