|
| 1 | +# Construct Tree from Inorder & Preorder |
| 2 | +## Medium |
| 3 | +<div class="problems_problem_content__Xm_eO"><p><span style="font-size:18px">Given 2 Arrays of Inorder and preorder traversal. The tree can contain duplicate elements. Construct a tree and print the Postorder traversal. </span></p> |
| 4 | + |
| 5 | +<p><strong><span style="font-size:18px">Example 1:</span></strong></p> |
| 6 | + |
| 7 | +<pre><strong><span style="font-size:18px">Input: |
| 8 | +</span></strong><span style="font-size:18px">N = 4 |
| 9 | +inorder[] = {1 6 8 7} |
| 10 | +preorder[] = {1 6 7 8} |
| 11 | +<strong>Output: </strong>8 7 6 1</span> |
| 12 | +</pre> |
| 13 | + |
| 14 | +<p><strong><span style="font-size:18px">Example 2:</span></strong></p> |
| 15 | + |
| 16 | +<pre><strong><span style="font-size:18px">Input: |
| 17 | +</span></strong><span style="font-size:18px">N = 6 |
| 18 | +inorder[] = {3 1 4 0 5 2} |
| 19 | +preorder[] = {0 1 3 4 2 5} |
| 20 | +<strong>Output: </strong>3 4 1 5 2 0<strong> |
| 21 | +Explanation: </strong>The tree will look like |
| 22 | + 0 |
| 23 | + / \ |
| 24 | + 1 2 |
| 25 | + / \ / |
| 26 | +3 4 5</span></pre> |
| 27 | + |
| 28 | +<p><span style="font-size:18px"><strong>Your Task:</strong><br> |
| 29 | +Your task is to complete the function <strong>buildTree() </strong>which takes 3 arguments(inorder traversal array, preorder traversal array, and size of tree n) and returns the root node to the tree constructed. You are not required to print anything and a new line is added automatically (The post order of the returned tree is printed by the driver's code.)</span></p> |
| 30 | + |
| 31 | +<p><span style="font-size:18px"><strong>Expected Time Complexity</strong>: O(N*N).<br> |
| 32 | +<strong>Expected Auxiliary Space:</strong> O(N).</span></p> |
| 33 | + |
| 34 | +<p><span style="font-size:18px"><strong>Constraints:</strong><br> |
| 35 | +1<=Number of Nodes<=1000</span></p> |
| 36 | +</div> |
0 commit comments