generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem22.cs
More file actions
47 lines (41 loc) · 1.73 KB
/
Problem22.cs
File metadata and controls
47 lines (41 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/">Construct Binary Tree from Preorder and Inorder Traversal</see>.
/// </summary>
public static class Problem22
{
/// <summary>
/// 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.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="preorder">Preorder array.</param>
/// <param name="inorder">Inorder array.</param>
/// <returns>Constructed binary tree.</returns>
public static TreeNode? BuildTree(int[] preorder, int[] inorder)
{
var inorderDict = new Dictionary<int, int>(inorder.Length);
for (var i = 0; i < inorder.Length; i++)
{
inorderDict.Add(inorder[i], i);
}
return BuildTree(preorder, 0, inorderDict, 0, inorder.Length - 1);
}
private static TreeNode? BuildTree(int[] preorder, int preorderIndex, Dictionary<int, int> inorderDict, int low, int high)
{
if (low > high)
{
return null;
}
var preorderElement = preorder[preorderIndex];
var inorderIndex = inorderDict[preorderElement];
var leftPreorderIndex = preorderIndex + 1;
var rightPreorderIndex = leftPreorderIndex + inorderIndex - low;
return new TreeNode(preorderElement)
{
Left = BuildTree(preorder, leftPreorderIndex, inorderDict, low, inorderIndex - 1),
Right = BuildTree(preorder, rightPreorderIndex, inorderDict, inorderIndex + 1, high),
};
}
}