From f55a8aa0026c0396344f8a0a64bb645fe93368e2 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Sat, 4 May 2024 21:59:07 +0530 Subject: [PATCH] Create 4 May Construct Binary Tree from Inorder and Postorder --- ...uct Binary Tree from Inorder and Postorder | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 4 May Construct Binary Tree from Inorder and Postorder diff --git a/4 May Construct Binary Tree from Inorder and Postorder b/4 May Construct Binary Tree from Inorder and Postorder new file mode 100644 index 00000000..ab2b76d9 --- /dev/null +++ b/4 May Construct Binary Tree from Inorder and Postorder @@ -0,0 +1,28 @@ +class Solution +{ + public: + + Node *solve(int in[], int post[], int inStart, int inEnd, int posStart, int posEnd) +{ + if (posEnd < 0 || inStart > inEnd) + return NULL; + Node *root = new Node(post[posEnd]); + int i = inStart; + for (; i <= inEnd; i++) + { + if (root->data == in[i]) + { + break; + } + } + int left = i - inStart; + int right = inEnd - i; + root->left = solve(in, post, inStart, i - 1, posStart, posStart + left - 1); + root->right = solve(in, post, i + 1, inEnd, posEnd - right, posEnd - 1); + return root; +} +Node *buildTree(int in[], int post[], int n) +{ + return solve(in, post, 0, n - 1, 0, n - 1); +} +};