From 4bd536bf882c9a11c63d37b3c25b36b3d443c4b2 Mon Sep 17 00:00:00 2001 From: rahulsingh522003 <85445665+rahulsingh522003@users.noreply.github.com> Date: Mon, 31 Oct 2022 09:17:36 +0530 Subject: [PATCH] Create Construct_binary_tree.cpp C++ prgoram to construct a binary tree using inorder and preorder traversal. --- C++/Construct_binary_tree.cpp | 55 +++++++++++++++++++++++++++++++++++ 1 file changed, 55 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..27091a4 --- /dev/null +++ b/C++/Construct_binary_tree.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; + +struct Node +{ + int key; + struct Node *left; + struct Node *right; + Node(int k) + { + key = k; + left = right = NULL; + } +}; + +void inorder(Node *root) +{ + if (root != NULL) + { + inorder(root->left); + cout << root->key << " "; + inorder(root->right); + } +} + +int preIndex = 0; +Node *cTree(int in[], int pre[], int is, int ie) +{ + if (is > ie) + return NULL; + Node *root = new Node(pre[preIndex++]); + + int inIndex; + for (int i = is; i <= ie; i++) + { + if (in[i] == root->key) + { + inIndex = i; + break; + } + } + root->left = cTree(in, pre, is, inIndex - 1); + root->right = cTree(in, pre, inIndex + 1, ie); + return root; +} + +int main() +{ + + int in[] = {20, 10, 40, 30, 50}; + int pre[] = {10, 20, 30, 40, 50}; + int n = sizeof(in) / sizeof(in[0]); + Node *root = cTree(in, pre, 0, n - 1); + inorder(root); +}