Recursion

Tree from Preorder and Inorder Traversal

Tree DFS

Given two integer arrays preorder and inorder containing the preorder and inorder traversals of a binary tree, construct the binary tree, and return its root. The values in the traversals will all be unique.

Example:

preorder = [3, 2, 9, 1, 4, 5]inorder = [9, 2, 1, 3, 4, 5]\notag \begin{align*} \texttt{preorder }&\texttt{= [3, 2, 9, 1, 4, 5]} \\ \texttt{inorder }&\texttt{= [9, 2, 1, 3, 4, 5]} \end{align*}
First Few Test Cases:

We want to create a function that takes in preorder\text{preorder} and inorder\text{inorder}, and returns the root node of the tree.

1. Recursion

To make this function recursive, buildTree\tt buildTree should call itself to construct the root.left\texttt{root.left} and root.right\texttt{root.right} nodes. You can draw the recursion visually as:

The next thing we have to do is figure out what pL, iL, pR, iR\small \text{pL, iL, pR, iR} and v\text{v} are. Here's a visual of how to do this - the idea is to look back and forth between the two arrays until we find everything:

We have everything we need for the recursion. Here's the recursion:

2. Base case

The recursion calls itself on smaller and smaller arrays, since it keeps splicing the input. The smallest case is when we get to two empty arrays - at this point, it means we're building a null node. (Note that the arrays will always be the same size).

3. Code

To code this, we just have to do is combine the recursion and base case:

Time Complexity O(n2)O(n^2). We visit each of the nn nodes once. At each node, we create the arrays pL,pR,iL,iR\tt pL, pR, iL, iR which all take O(n)O(n) operations. We also call inorder.index(v)\texttt{inorder.index(v)} which is also O(n)O(n). Adding this all up, the total operations per function call is O(5n)O(5n) and we call the function nn times. This means the total time is O(5n)n=O(n2)O(5n)*n = O(n^2).

Space Complexity O(n2)O(n^2). The Call Stack grows to the height of the tree, which is nn. Each call in the Call Stack needs to remember its inputs, which are both size O(n)O(n) arrays. This gives O(n2)O(n^2) memory.

This solution should pass in an interview (I got a FAANG job with it), but you can make some optimizations. If you're curious what they are, see the spoiler below.

Mark as Completed:
Submits:
buildTree
Imports:
TreeNode
Test your code to get an output here!
buildTree(
)
Test your code to get an output here!