-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
86 lines (79 loc) · 1.94 KB
/
Solution.cs
File metadata and controls
86 lines (79 loc) · 1.94 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class BSTIterator
{
Stack<TreeNode> _stack;
public BSTIterator(TreeNode root)
{
_stack = [];
UpdateStack(root);
}
private void UpdateStack(TreeNode root)
{
if (root == null) return;
_stack.Push(root);
while (root.left != null)
{
_stack.Push(root.left);
root = root.left;
}
}
public int Next()
{
if (HasNext())
{
TreeNode curr = _stack.Pop();
UpdateStack(curr.right);
return curr.val;
}
return int.MaxValue;
}
public bool HasNext()
{
return _stack.Count > 0;
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.Next();
* bool param_2 = obj.HasNext();
*/
public class Solution
{
public List<dynamic> Execute(string[] actions, int?[][][] values)
{
List<dynamic> result = [];
BSTIterator bst = new(null);
for (int i = 0; i < actions.Length; i++)
{
switch (actions[i])
{
case "BSTIterator":
bst = new BSTIterator(TreeNodeHelper.CreateTreeFromArray(values[i][0]));
result.Add(null);
break;
case "next":
result.Add(bst.Next());
break;
case "hasNext":
result.Add(bst.HasNext());
break;
default:
break;
}
}
return result;
}
}