TreeNode* buildTreeUtil(int iBegin, int iEnd, int pEnd, vector<int>& inorder, vector<int>& postorder) { if (iBegin > iEnd) return NULL; TreeNode* root = new TreeNode(postorder[pEnd]); int i = iBegin; for ( ; i <= iEnd && inorder[i] != root->val; i++); root->left = buildTreeUtil(iBegin, i - 1, pEnd + i - 1 - iEnd, inorder, postorder); root->right = buildTreeUtil(i + 1, iEnd, pEnd - 1, inorder, postorder); return root; }
TreeNode *buildTreeUtil(vector<int> &preorder, int &preid, vector<int> &inorder, int l, int r){ if(l>r)return NULL; if(preid >= preorder.size())return NULL; if(l==r){ preid++; return new TreeNode(inorder[l]); } TreeNode *root = new TreeNode(preorder[preid]); int i; for(i=l;i<=r;i++){ if(inorder[i] == preorder[preid]){ preid++; break; } } root->left = buildTreeUtil(preorder, preid, inorder, l, i-1); root->right = buildTreeUtil(preorder, preid, inorder, i+1, r); return root; }
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { int preid = 0; return buildTreeUtil(preorder, preid, inorder, 0, inorder.size()-1); }
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if (inorder.empty()) return NULL; return buildTreeUtil(0, inorder.size() - 1, postorder.size() - 1, inorder, postorder); }