C# || How To Construct Binary Tree From Preorder And Inorder Traversal Using C#

The following is a module with functions which demonstrates how to construct a binary tree from pre order and in order traversal using C#.


1. Build Tree – Problem Statement

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.

Example 1:

Example 1


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

Example 2:


Input: preorder = [-1], inorder = [-1]
Output: [-1]


2. Build Tree – Solution

The following is a solution which demonstrates how to construct a binary tree from pre order and in order traversal.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


[3,9,20,null,null,15,7]
[-1]

Was this article helpful?
👍 YesNo

Leave a Reply