-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy path0173-BinarySearchTreeIterator.cs
47 lines (39 loc) · 1.16 KB
/
0173-BinarySearchTreeIterator.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
//-----------------------------------------------------------------------------
// Runtime: 156ms
// Memory Usage: 40.4 MB
// Link: https://leetcode.com/submissions/detail/261196329/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0173_BinarySearchTreeIterator
{
private readonly Stack<TreeNode> stack;
public _0173_BinarySearchTreeIterator(TreeNode root)
{
stack = new Stack<TreeNode>();
LeftMostInorder(root);
}
private void LeftMostInorder(TreeNode root)
{
while (root != null)
{
stack.Push(root);
root = root.left;
}
}
/** @return the next smallest number */
public int Next()
{
var node = stack.Pop();
if (node.right != null)
LeftMostInorder(node.right);
return node.val;
}
/** @return whether we have a next smallest number */
public bool HasNext()
{
return stack.Count > 0;
}
}
}