1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if(inorder.empty()) return nullptr; return build(inorder, 0, inorder.size(), postorder, 0, postorder.size()); } TreeNode* build(vector<int>& inorder, int inBegin, int inEnd, vector<int>& postorder, int poBegin, int poEnd) { if(poBegin == poEnd) return nullptr; int val = postorder[poEnd - 1]; TreeNode* root = new TreeNode(val); if(poEnd - poBegin == 1) return root;
int target; for(target = inBegin; target < inEnd; ++target) if(inorder[target] == val) break; int leftinBegin = inBegin, leftinEnd = target; int righrinBegin = target + 1, rightinEnd = inEnd; int leftpoBegin = poBegin, leftpoEnd = poBegin + target - inBegin; int rightpoBegin = leftpoEnd, rightpoEnd = poEnd - 1;
root->left = build(inorder, leftinBegin, leftinEnd, postorder,leftpoBegin, leftpoEnd);
root->right = build(inorder, righrinBegin, rightinEnd, postorder, rightpoBegin, rightpoEnd);
return root; }
|