45. Construct a BT from Preorder and Inorder

Given two integer arrays preorder and inorder. Where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree.

Construct and return the binary tree using in-order and preorder arrays.

Example 1:

Input : preorder = [3, 9, 20, 15, 7] , inorder = [9, 3, 15, 20, 7]

Output : [3, 9, 20, null, null, 15, 7]

Explanation : The output tree is shown below.

Example 2:

Input : preorder = [3, 4, 5, 6, 2, 9] , inorder = [5, 4, 6, 3, 2, 9]

Output : [3, 4, 2, 5, 6, null, 9]

Explanation : The output tree is shown below.

Now Your Turn!

Pick the correct output for the given input

Input : preorder = [5, 1, 8, 6, 2, 4, 7] , inorder = [8, 6, 1, 5, 4, 2, 7]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 104
  • -104 <= Node.val <= 104
  • All values in the given tree are unique.
  • Each value of inorder also appears in preorder.
  • Preorder is guaranteed to be the preorder traversal of the tree.
  • Inorder is guaranteed to be the inorder traversal of the tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
//your code goes here
}
};
Test Case

Input:

Inorder
Preorder