diff --git a/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/Solution.cpp b/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/Solution.cpp new file mode 100644 index 0000000000000..50119b1c3865a --- /dev/null +++ b/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/Solution.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + TreeNode *buildTree(vector &inorder, vector &postorder) { + return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); + } + TreeNode *buildTree(vector &inorder, int iLeft, int iRight, vector &postorder, int pLeft, int pRight) { + if (iLeft > iRight || pLeft > pRight) return NULL; + TreeNode *cur = new TreeNode(postorder[pRight]); + int i = 0; + for (i = iLeft; i < inorder.size(); ++i) { + if (inorder[i] == cur->val) + break; + } + cur->left = buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1); + cur->right = buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1); + return cur; + } +}; \ No newline at end of file