From 08b9a8bbf02ae6f73df65f9d6b28b6737cf7dfe9 Mon Sep 17 00:00:00 2001 From: Swapnil0803 <109861486+Swapnil0803@users.noreply.github.com> Date: Sat, 15 Oct 2022 18:54:10 +0530 Subject: [PATCH] Create Construct_Binary_Tree.cpp Added solution for the binary tree construction using inorder and postorder traversal --- C++/Construct_Binary_Tree.cpp | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/Construct_Binary_Tree.cpp diff --git a/C++/Construct_Binary_Tree.cpp b/C++/Construct_Binary_Tree.cpp new file mode 100644 index 0000000..b85271c --- /dev/null +++ b/C++/Construct_Binary_Tree.cpp @@ -0,0 +1,44 @@ +// Construction of the binary tree from inorder and postorder traversal in c++ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* buildTree(vector& in, vector& post) { + unordered_map pos; + int n = post.size(); + for (int i = 0; i < n; i++) { + pos[in[i]] = i; + } + TreeNode* root = NULL; + for (int i = n - 1; i >= 0; i--) { + int num = post[i], p = pos[num]; + //cout << num << ":" << p << endl; + TreeNode* tr = new TreeNode(num); + if (i == n - 1) { + root = tr; + continue; + } + TreeNode* node = root, *prev = NULL; + while (node) { + prev = node; + if (pos[node->val] > p) node = node->left; + else node = node->right; + } + node = tr; + if (pos[prev->val] > p) prev->left = tr; + else prev->right = tr; + } + return root; + } +}; +// This is contributed by - Swapnil0803