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
|
class Solution { public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return buildTreeImpl(inorder, 0, inorder.size(), postorder, 0, postorder.size()); } TreeNode* buildTreeImpl(vector<int> &inorder, int inStart, int inEnd, vector<int> &postorder, int postStart, int postEnd){ if(inStart == inEnd || postStart == postEnd) return nullptr; int rootVal = postorder[postEnd - 1]; TreeNode *root = new TreeNode(rootVal); int leftLen, rightLen; for(int i = inStart; i < inEnd; i++){ if(inorder[i] == rootVal){ leftLen = i - inStart; break; } } rightLen = (inEnd - inStart - leftLen - 1); root->left = buildTreeImpl(inorder, inStart, inStart + leftLen, postorder, postStart, postStart + leftLen); root->right = buildTreeImpl(inorder, inStart + leftLen + 1, inEnd, postorder, postStart + leftLen, postEnd - 1); return root; } };
|