105. Construct Binary Tree from Preorder and Inorder Traversal

Medium

Problem:

Given the preorder and inorder traversal results of a tree as input, construct the binary tree.

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/arrow-up-right

Solution:

There are primarily three types of tree traversals: preorder, inorder, and postorder. With just any two of these traversals, a binary tree can be restored.

The first value in the preorder is the parent node. In other words, the first result of the preorder traversal precisely divides the inorder traversal result into left and right. Essentially, this converts the problem into a divide-and-conquer based on inorder traversal.

Note: In Python, the list can take an index for the pop() function, essentially performing the roles of both a stack and a queue. However, using pop(0) has a time complexity of O(n)O(n).

Last updated