-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1008-ConstructBinarySearchTreeFromPreorderTraversal.cs
48 lines (40 loc) · 1.28 KB
/
1008-ConstructBinarySearchTreeFromPreorderTraversal.cs
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
48
//-----------------------------------------------------------------------------
// Runtime: 88ms
// Memory Usage: 24.4 MB
// Link: https://leetcode.com/submissions/detail/327815703/
//-----------------------------------------------------------------------------
namespace LeetCode
{
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class _1008_ConstructBinarySearchTreeFromPreorderTraversal
{
private int[] preorder;
private int index;
public TreeNode BstFromPreorder(int[] preorder)
{
this.preorder = preorder;
index = 0;
return Build(int.MinValue, int.MaxValue);
}
private TreeNode Build(int minValue, int maxValue)
{
if (index >= preorder.Length) return null;
var value = preorder[index];
if (value < minValue || value > maxValue)
return null;
var root = new TreeNode(value);
index++;
root.left = Build(minValue, value);
root.right = Build(value, maxValue);
return root;
}
}
}